﻿/*ESRPConnectionString*/
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
/*Modificari pana la data de 01.01.2011*/
/**/

IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[fares_Facturi]'))
DROP VIEW [dbo].[fares_Facturi]
GO


CREATE VIEW [dbo].[fares_Facturi]
AS
SELECT     a.IDPartener, a.NrDoc, a.DataDoc, ROUND(a.TotalValoare, 2) AS TotalValoare, ROUND(a.TotalValoareTVA, 2) AS TotalValoareTVA, ROUND(a.Total, 2) AS Total, 
                      COALESCE (b.Valoare, 0) AS Valoare, ROUND(a.Total, 2) - COALESCE (b.Valoare, 0) AS RestPlata, a.DataScadenta, dbo.Parteneri.Denumire, a.IDTipDocument, 
                      a.CodUnitate, CAST(a.IDDocument AS varchar(50)) AS IDDocument
FROM         dbo.Documente AS a LEFT OUTER JOIN
                          (SELECT     IDDocument, SUM(Valoare) AS Valoare
                            FROM          dbo.DocumentePlataDetaliu
                            GROUP BY IDDocument) AS b ON a.IDDocument = b.IDDocument INNER JOIN
                      dbo.Parteneri ON a.IDPartener = dbo.Parteneri.IDPartener

GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'RegimFiscal' AND COLUMN_NAME = 'IntraIn394')
BEGIN
ALTER TABLE dbo.RegimFiscal ADD
	IntraIn394 bit NOT NULL CONSTRAINT DF_RegimFiscal_IntraIn394 DEFAULT 1
END
GO


IF NOT  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Gestionari]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Gestionari](
		[IDGestionar] [int] IDENTITY(1,1) NOT NULL,
		[NumePrenume] [varchar](100) NOT NULL,
	 CONSTRAINT [PK_Gestionari] PRIMARY KEY CLUSTERED 
	(
		[IDGestionar] ASC
	) ON [PRIMARY]
	) ON [PRIMARY]
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Departamente' AND COLUMN_NAME = 'IDGestionar')
BEGIN
ALTER TABLE dbo.Departamente ADD
	IDGestionar int NULL

ALTER TABLE dbo.Departamente ADD CONSTRAINT
	FK_Departamente_Gestionari FOREIGN KEY
	(
	IDGestionar
	) REFERENCES dbo.Gestionari
	(
	IDGestionar
	) ON UPDATE  NO ACTION 
	 ON DELETE  NO ACTION 
END	
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'IDGestionar')
BEGIN
	ALTER TABLE dbo.Documente ADD
		IDGestionar int NULL

	ALTER TABLE dbo.Documente ADD CONSTRAINT
		FK_Documente_Gestionari FOREIGN KEY
		(
		IDGestionar
		) REFERENCES dbo.Gestionari
		(
		IDGestionar
		) ON UPDATE  NO ACTION 
		 ON DELETE  NO ACTION 
	
END
GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010')
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010' AND COLUMN_NAME = 'IDGestionar')
BEGIN
	ALTER TABLE dbo.Documente2010 ADD
		IDGestionar int NULL

	ALTER TABLE dbo.Documente2010 ADD CONSTRAINT
		FK_Documente2010_Gestionari FOREIGN KEY
		(
		IDGestionar
		) REFERENCES dbo.Gestionari
		(
		IDGestionar
		) ON UPDATE  NO ACTION 
		 ON DELETE  NO ACTION 
	
END
GO

IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[InchidereConturiVenituriCheltuieli]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[InchidereConturiVenituriCheltuieli]
GO

CREATE PROCEDURE [dbo].[InchidereConturiVenituriCheltuieli] 
	-- Add the parameters for the stored procedure here
	@DataDoc DATETIME,
	@DeLaData DATETIME,
	@PanaLaData DATETIME,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	DECLARE @NrDocAdd int
	DECLARE @LastNrDoc bigint
	SET NOCOUNT ON;
    BEGIN TRAN
    
    DECLARE my_cursor CURSOR FOR 
	SELECT
	ValoareLei,
	0 AS ValoareValuta,
	NumarDoc NumarDoc,
	@DataDoc AS DataDoc,
	'IC' AS NumarNota,
	2 AS TipFormula,
	IdJurnal,
	Cont,
	CASE WHEN Cont = '6' THEN 'Inchidere cont de cheltuieli' WHEN Cont='7' THEN 'Inchidere cont de venituri' ELSE '' END AS Observatii
	FROM (SELECT 
		ABS(SUM(soldd)) ValoareLei,
		Cont,IDJurnal,(SELECT Max(NumarDoc) FROM [RulajeDoc] WHERE [CodUnitate]=@CodUnitate) NumarDoc
		FROM
			(SELECT SUM(a.ValoareLei) soldd, dbo.GetContClass(ContDebit) Cont,IDJurnal FROM Rulaje a
			JOIN RulajeDoc b ON a.IdDocument=b.IdDocument 
			WHERE b.DataDoc>=@DeLaData AND b.DataDoc <=@PanaLaData AND a.[CodUnitate] = @CodUnitate
			GROUP BY dbo.GetContClass(ContDebit),IDJurnal
			UNION
			SELECT -SUM(a.ValoareLei) soldd, dbo.GetContClass(ContCredit) Cont,IDJurnal FROM Rulaje a
			JOIN RulajeDoc b ON a.IdDocument=b.IdDocument 
			WHERE b.DataDoc>=@DeLaData AND b.DataDoc <=@PanaLaData  AND a.[CodUnitate] = @CodUnitate
			GROUP BY dbo.GetContClass(ContCredit),IDJurnal) t1
		WHERE Cont>='6' AND Cont<='7' AND soldd<>0
		GROUP BY Cont,IDJurnal) t2
	WHERE ValoareLei<>0

	OPEN my_cursor;
	
	DECLARE @valoarelei decimal(20,2),@valoarevaluta decimal(20,2),@nrdoc decimal(18,0)
	DECLARE @numarNota varchar(50),@observatii varchar(200),@clasacont varchar(1)
	DECLARE @idjurnal int
	DECLARE @tipformula smallint
	DECLARE @datadoc1 datetime 
	

	FETCH NEXT FROM my_cursor 
	INTO @valoarelei,@valoarevaluta,@nrdoc,@DataDoc1,@numarNota,@tipformula,@idjurnal,@clasacont,@observatii;

	WHILE @@FETCH_STATUS = 0
	BEGIN


	INSERT INTO [RulajeDoc]
	([ValoareLei],[ValoareValuta],[NumarDoc],[DataDoc],[NumarNota],[TipFormula],[IDJurnal]
	,[Observatii],[xUser],[xHost],[CodUnitate])   
	VALUES (@valoarelei,@valoarevaluta,@nrdoc,@DataDoc1,@numarNota,@tipformula,@idjurnal,@observatii,
	system_user,host_name(),@CodUnitate)
	

    PRINT(SCOPE_IDENTITY())
	PRINT(@NrDocAdd)
	PRINT(@DeLaData)
	PRINT(@PanaLaData)
	
    --PRINT(@LastNrDoc)
	IF @@ERROR <>0  GOTO EroareDoc
		INSERT INTO [Rulaje]
		([ContDebit],[ContCredit],[CodValuta],[IDDocument] ,[ValoareValuta],[Curs],[ValoareLei],[DataDocJust]
			,[TipDocJust] ,[NumarDocJust] ,[ExplicatiiDocJust] ,[NrCrt],[CodUnitate])
			SELECT 
			CASE WHEN SCont = '7' THEN Cont WHEN SCont='6' THEN t3.ContDebit ELSE 'N/A' END ContDebit,
			CASE WHEN SCont = '7' THEN t3.ContCredit WHEN SCont='6' THEN Cont ELSE 'N/A' END ContCredit,
			0 AS CodValuta,
			SCOPE_IDENTITY() AS IDDocument,
			0 AS ValoareValuta,
			0 AS Curs,
			ValoareLei,
			@DataDoc AS DataDocJust,
			'IC' AS TipDocJust,
			0 AS NumarDocJust,
			'Inchidere Conturi'  AS ExplicatiiDocJust,
			0 AS NrCrt,
			@CodUnitate AS CodUnitate
			FROM (SELECT 
					CASE WHEN SCont='6' THEN SUM(soldd) ELSE -SUM(soldd) END ValoareLei,SCont,[CodUnitate],
					Cont,IDJurnal, @@IDENTITY AS NumarDoc,
					0 RowNumber FROM
						(SELECT SUM(a.ValoareLei) soldd, ContDebit Cont,dbo.GetContClass(ContDebit) SCont,IDJurnal,a.[CodUnitate] FROM Rulaje a
						JOIN RulajeDoc b ON a.IdDocument=b.IdDocument 
						WHERE b.DataDoc>=@DeLaData AND b.DataDoc <=@PanaLaData AND a.[CodUnitate]=@CodUnitate AND b.IDJurnal=@idjurnal
						GROUP BY ContDebit,dbo.GetContClass(ContDebit),IDJurnal,a.[CodUnitate]
						UNION
						SELECT -SUM(a.ValoareLei) soldd, ContCredit Cont,dbo.GetContClass(ContCredit) SCont,IDJurnal,a.[CodUnitate] FROM Rulaje a
						JOIN RulajeDoc b ON a.IdDocument=b.IdDocument 
						WHERE b.DataDoc>=@DeLaData AND b.DataDoc <=@PanaLaData  AND a.[CodUnitate]=@CodUnitate  AND b.IDJurnal=@idjurnal
						GROUP BY ContCredit,dbo.GetContClass(ContCredit),IDJurnal,a.[CodUnitate]) t1
					WHERE dbo.GetContClass(Cont)= @clasacont AND soldd<>0
					GROUP BY Cont,SCont,IDJurnal,[CodUnitate]) t2 
                    JOIN ConturiCoresp t3 
                    ON ((t3.ContDebit = t2.Cont) OR (t3.ContCredit = t2.Cont)) AND t3.IDJurnal = t2.IdJurnal AND t3.CodUnitate=t2.CodUnitate
			   	  					
		WHERE ValoareLei<>0 
		IF @@ERROR <>0  GOTO EroareRul
		
		FETCH NEXT FROM my_cursor 
			INTO @valoarelei,@valoarevaluta,@nrdoc,@DataDoc1,@numarNota,@tipformula,@idjurnal,@clasacont,@observatii;
	END
	CLOSE my_cursor;
	DEALLOCATE my_cursor;		
		
		
		COMMIT TRAN
	GOTO Gata
	EroareDoc:
		ROLLBACK
		RAISERROR('Eroare la generarea documentului ',16,-1)
		return
	EroareRul:
		ROLLBACK
		RAISERROR('Eroare la generarea rulajului ',16,-1)
		return

	Gata:
END

GO


/****** Object:  StoredProcedure [dbo].[CalcDisponibilPAC]    Script Date: 07/27/2011 21:33:50 ******/
IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[CalcDisponibilPAC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CalcDisponibilPAC]
GO


CREATE PROCEDURE [dbo].[CalcDisponibilPAC]
	@CodUnitate smallint,
	@IDPAC int,
	@Data datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	UPDATE [PropunereAngajareCheltuialaDetaliu] SET [CredBugAprob]= 
	(SELECT coalesce(SUM(ValoareLei),0) FROM [Rulaje] r JOIN ExBugSetup es ON es.CodUnitate=r.CodUnitate
	 WHERE (IDDocument IN 
	 (SELECT IDDocument FROM RulajeDoc rd  WHERE
		IDJurnal = [PropunereAngajareCheltuialaDetaliu].[IDJurnal] AND [CodUnitate]=@CodUnitate AND DataDoc<=@Data)) AND ContDebit= es.ContAB + '.'+[PropunereAngajareCheltuialaDetaliu].[ArtAl])
		
		-(SELECT coalesce(SUM(ValoareLei),0) FROM [Rulaje] r JOIN ExBugSetup es ON es.CodUnitate=r.CodUnitate WHERE (IDDocument IN 
		(SELECT IDDocument FROM RulajeDoc WHERE
		IDJurnal = [PropunereAngajareCheltuialaDetaliu].[IDJurnal] AND [CodUnitate]=@CodUnitate AND DataDoc<=@Data)) AND ContCredit= es.ContAB + '.'+[PropunereAngajareCheltuialaDetaliu].[ArtAl])
		WHERE [IDPac]=@IDPAC

	UPDATE [PropunereAngajareCheltuialaDetaliu] SET [CredBugAngaj]= (SELECT coalesce(SUM(ValoareLei),0) FROM [Rulaje] 
	r JOIN ExBugSetup es ON es.CodUnitate=r.CodUnitate WHERE (IDDocument IN (SELECT IDDocument FROM RulajeDoc WHERE
		IDJurnal = [PropunereAngajareCheltuialaDetaliu].[IDJurnal] AND [CodUnitate]=@CodUnitate  AND DataDoc<@Data)) AND ContDebit= es.ContAL +'.'+[PropunereAngajareCheltuialaDetaliu].[ArtAl])
		-(SELECT coalesce(SUM(ValoareLei),0) FROM [Rulaje] r JOIN ExBugSetup es ON es.CodUnitate=r.CodUnitate WHERE (IDDocument IN (SELECT IDDocument FROM RulajeDoc WHERE
		IDJurnal = [PropunereAngajareCheltuialaDetaliu].[IDJurnal] AND [CodUnitate]=@CodUnitate  AND DataDoc<@Data)) AND ContCredit= es.ContAL + '.'+[PropunereAngajareCheltuialaDetaliu].[ArtAl]) 
		--+(SELECT COALESCE(sum(Suma),0) FROM [PropunereAngajareCheltuialaDetaliu] a JOIN [PropunereAngajareCheltuiala] b ON a.IDPac=b.IDPAC  WHERE a.[IDPACDetaliu] < [PropunereAngajareCheltuialaDetaliu].[IDPACDetaliu] AND a.ArtAl = [PropunereAngajareCheltuialaDetaliu].[ArtAl]
		--AND b.Data < @Data)
		WHERE [IDPac]=@IDPAC
		
		
	UPDATE [PropunereAngajareCheltuialaDetaliu] SET [Clasif]=LTRIM(RTRIM(j.[Codificare]))+'.' +dbo.GetTitlu([ArtAl])+'.' + LTRIM(RTRIM([ArtAl]))  FROM [Jurnale] j WHERE j.[IDJurnal] = [PropunereAngajareCheltuialaDetaliu] .[IDJurnal] AND [IDPAC] =@IDPAC
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TipDepartament' AND COLUMN_NAME = 'Amanunt')
BEGIN
	
	ALTER TABLE dbo.TipDepartament ADD Amanunt bit NOT NULL DEFAULT 0
		
END
GO


DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9'
IF @Cate<> 0 
begin
	DELETE  FROM [admin_ApplicationMenu] WHERE [ApplicationId]='892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9' AND [HandlerName]='Tipuri_Departamente'
	DELETE  FROM [admin_ApplicationMenu] WHERE [ApplicationId]='892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9' AND [HandlerName]='Departamente'
	DELETE  FROM [admin_ApplicationMenu] WHERE [ApplicationId]='892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9' AND [HandlerName]='Tipuri_Documente'
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(3411,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Tipuri Gestiuni',3400,30,'Tipuri_Departamente',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(3412,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Gestiuni',3400,31,'Departamente',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(3413,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Tipuri Documente',3400,32,'Tipuri_Documente',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 
go

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'AfiseazaSemnaturiTiparire')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD AfiseazaSemnaturiTiparire bit NOT NULL DEFAULT 1
END
GO


DECLARE @cateBC int
SELECT @CateBC = COUNT(*) FROM [TipDocument] WHERE [IDTipDocument]=13
IF @CateBC= 0 
begin
	SET IDENTITY_INSERT [TipDocument] ON
	INSERT INTO [TipDocument] ([IDTipDocument],[Denumire],[TipOperatie],[SePlateste]) VALUES (13,'Bon de consum','O',0)
	SET IDENTITY_INSERT [TipDocument] OFF
END
GO

DECLARE @cateBC int
SELECT @CateBC = COUNT(*) FROM [admin_ApplicationDocuments] WHERE [IDTipDocument]=13
IF @CateBC = 0 
begin
	INSERT INTO [admin_ApplicationDocuments] ([IDTipDocument],[ApplicationID]) VALUES (13,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9')
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Gestionari' AND COLUMN_NAME = 'Cod')
BEGIN
	ALTER TABLE dbo.Gestionari ADD Cod varchar(20) NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'IDPredator')
BEGIN
	ALTER TABLE dbo.Documente ADD
		IDPredator int NULL

	ALTER TABLE dbo.Documente ADD CONSTRAINT
		FK_Documente_Predator FOREIGN KEY
		(
		IDPredator
		) REFERENCES dbo.Gestionari
		(
		IDGestionar
		) ON UPDATE  NO ACTION 
		 ON DELETE  NO ACTION 
	
END
GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010')
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010' AND COLUMN_NAME = 'IDPredator')
BEGIN
	ALTER TABLE dbo.Documente2010 ADD
		IDPredator int NULL

	ALTER TABLE dbo.Documente2010 ADD CONSTRAINT
		FK_Documente2010_Predator FOREIGN KEY
		(
		IDPredator
		) REFERENCES dbo.Gestionari
		(
		IDGestionar
		) ON UPDATE  NO ACTION 
		 ON DELETE  NO ACTION 
	
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'IDSerieBC')
BEGIN
ALTER TABLE dbo.FaresSetup ADD
	IDSerieBC varchar(20) NOT NULL DEFAULT ''
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'IDSerieBF')
BEGIN
ALTER TABLE dbo.FaresSetup ADD
	IDSerieBF varchar(20) NOT NULL DEFAULT ''
END
GO


ALTER TRIGGER [dbo].[audit_Document] 
   ON  [dbo].[Documente]
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @modifDoc bit
	SELECT @modifDoc = SalveazaCuUrmatorulNumar FROM FaresSetup a JOIN inserted i ON
		a.[CodUnitate]=i.CodUnitate
	IF @modifDoc=1
		UPDATE [Documente] SET NrDoc = (SELECT MAX(CAST([NrDoc] AS decimal(18,0)))+1 FROM [Documente] a WHERE 
			a.CodUnitate=[Documente].[CodUnitate] AND a.IDTipDocument = [Documente].IDTipDocument) FROM inserted i
		WHERE i.IDDocument=[Documente].[IDDocument]  AND 
		NOT EXISTS(SELECT * FROM deleted d WHERE d.IDDocument=i.IDDocument)

    INSERT INTO [admin_Audit]
           ([UserId]
           ,[TableName]
           ,[Operation]
           ,[CampID]
           ,[Data])
     SELECT [UserID],'Documente', 'A', IDDocument, getdate() FROM inserted i
		WHERE i.IDDocument not in (SELECT IDDocument from deleted)	 

    INSERT INTO [admin_Audit]
           ([UserId]
           ,[TableName]
           ,[Operation]
           ,[CampID]
           ,[Data])
     SELECT i.[UserID],'Documente', 'M', i.IDDocument, getdate() FROM inserted i
		JOIN deleted d on i.IDDocument=d.IDDocument

    INSERT INTO [admin_Audit]
           ([UserId]
           ,[TableName]
           ,[Operation]
           ,[CampID]
           ,[Data])
     SELECT [UserID],'Documente', 'D', IDDocument, getdate() FROM deleted d
		WHERE d.IDDocument not in (SELECT IDDocument from inserted)	 

	

END
GO

IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Stocuri]') AND type in (N'U'))
BEGIN
	DECLARE @cate int
	SELECT @Cate = COUNT(*) FROM [Stocuri]
	IF @Cate =  0 
	begin
	DROP TABLE [dbo].[Stocuri]

	CREATE TABLE [dbo].[Stocuri](
		[IDStoc] [int] IDENTITY(1,1) NOT NULL,
		[IDArticol] [int] NOT NULL,
		[CodUnitate] [smallint] NOT NULL,
		[Pret] [decimal](25, 5) NOT NULL DEFAULT 0,
		[StocInitial] [decimal](25, 5) NOT NULL DEFAULT 0,
		[StocPrecedent] [decimal](25, 5) NOT NULL DEFAULT 0,
		[IDDepartament] [int] NULL,
		[IDVarinataArticol] [int] NULL,
	 CONSTRAINT [PK_Stocuri] PRIMARY KEY CLUSTERED 
	(
		[IDStoc] ASC
	)ON [PRIMARY],
	CONSTRAINT [FK_Stocuri_Articole] FOREIGN KEY([IDArticol]) REFERENCES [dbo].[Articole] ([IDArticol]),
	CONSTRAINT [FK_Stocuri_ArticoleVariante] FOREIGN KEY([IDVarinataArticol]) REFERENCES [dbo].[ArticoleVariante] ([IDVariantaArticol]),
	CONSTRAINT [FK_Stocuri_Departamente] FOREIGN KEY([IDDepartament]) REFERENCES [dbo].[Departamente] ([IDDepartament]),
	CONSTRAINT [FK_Stocuri_Unitati] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])
	) ON [PRIMARY]

	END
END
GO


DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='E03B2883-43E3-41B7-A41E-A620126D1BE0'
PRINT(@Cate)
IF @Cate<> 0 
begin
	DELETE  FROM [admin_ApplicationMenu] WHERE [ApplicationId]='E03B2883-43E3-41B7-A41E-A620126D1BE0' AND [HandlerName]='Calculatoare'
	--DELETE  FROM [admin_ApplicationMenu] WHERE [ApplicationId]='E03B2883-43E3-41B7-A41E-A620126D1BE0' AND [HandlerName]='Departamente'
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1060,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Interventii IT',null,85,'Calculatoare',NULL,NULL)
	--INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(3412,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Gestiuni',3400,31,'Departamente',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 
go

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Sisteme')
IF NOT  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SistemeUtilizatori]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SistemeUtilizatori](
		[IDSistem] [int] NOT NULL,
		[IDPersoana] [int] NOT NULL,
	 CONSTRAINT [PK_SistemeUtilizatori] PRIMARY KEY CLUSTERED 
	(
		[IDSistem] ASC,
		[IDPersoana] ASC
	)ON [PRIMARY],
	CONSTRAINT [FK_SistemeUtilizatori_Sisteme] FOREIGN KEY([IDSistem]) REFERENCES [dbo].[Sisteme] ([IDSistem]),
	CONSTRAINT [FK_SistemeUtilizatori_Persoane] FOREIGN KEY([IDPersoana]) REFERENCES [dbo].[Persoane] ([IdPersoana])

	) ON [PRIMARY]

END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Unitati' AND COLUMN_NAME = 'JudRegComert')
BEGIN
	ALTER TABLE dbo.Unitati ADD JudRegComert smallint NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Unitati' AND COLUMN_NAME = 'NrRegComert')
BEGIN
	ALTER TABLE dbo.Unitati ADD NrRegComert int NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Unitati' AND COLUMN_NAME = 'AnRegComert')
BEGIN
	ALTER TABLE dbo.Unitati ADD AnRegComert smallint NULL 
END
GO

IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[fares_ViewParteneri]'))
DROP VIEW [dbo].[fares_ViewParteneri]
GO


CREATE VIEW [dbo].[fares_ViewParteneri]
AS
SELECT     dbo.Parteneri.Denumire, dbo.Parteneri.Strada, dbo.Parteneri.Nr, dbo.Judete.Nume AS Judet, a.Nume AS Localitate, dbo.Parteneri.CodPostal, dbo.Parteneri.Telefon, 
                      dbo.Parteneri.IDPartener, dbo.Parteneri.Fax, dbo.Parteneri.AtributFiscal, dbo.Parteneri.JudetRegComert, dbo.Parteneri.NrRegComert, dbo.Parteneri.AnRegComert, 
                      dbo.Parteneri.NumeDelegat, dbo.Parteneri.SerieAI, dbo.Parteneri.NrAI, dbo.Parteneri.MijlocTransport, dbo.Parteneri.NrMijlocTransport, dbo.Banci.Denumire AS DenumireBanca, 
                      dbo.Parteneri.ContBancar, dbo.Parteneri.CUI
FROM         dbo.Parteneri INNER JOIN
                      dbo.Judete ON dbo.Parteneri.IDJudet = dbo.Judete.IDJudet INNER JOIN
                      dbo.Localitati AS a ON dbo.Parteneri.IDLocalitate = a.IDLocalitate LEFT OUTER JOIN
                      dbo.Banci ON dbo.Parteneri.IDBanca = dbo.Banci.IdBanca

GO

IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[fares_viewArticoleComanda]'))
DROP VIEW [dbo].[fares_viewArticoleComanda]
GO


CREATE VIEW [dbo].[fares_viewArticoleComanda]
AS
SELECT     dbo.Articole.Denumire, dbo.ArticoleParteneri.CodArticol, dbo.Articole.CodArticol AS MyCodArticol, dbo.Documente.IDDocument, dbo.Articole.CodCPV, 
                      dbo.UnitatiMasura.Denumire AS UM, dbo.DocumenteDetaliu.Cantitate, dbo.DocumenteDetaliu.ValoareUnitara, dbo.DocumenteDetaliu.IDArticol, 
                      dbo.DocumenteDetaliu.Cantitate * dbo.DocumenteDetaliu.ValoareUnitara AS ValoareTotala, dbo.DocumenteDetaliu.TermenLivrare, 
                      dbo.DocumenteDetaliu.IDDocumentDetaliu, dbo.ArticoleVariante.Denumire AS Varianta, dbo.DocumenteDetaliu.Observatii, dbo.DocumenteDetaliu.ValoareTVA
FROM         dbo.DocumenteDetaliu INNER JOIN
                      dbo.Articole ON dbo.DocumenteDetaliu.IDArticol = dbo.Articole.IDArticol INNER JOIN
                      dbo.UnitatiMasura ON dbo.DocumenteDetaliu.IDUnitateMasura = dbo.UnitatiMasura.IDUnitateMasura INNER JOIN
                      dbo.Documente ON dbo.DocumenteDetaliu.IDDocument = dbo.Documente.IDDocument LEFT OUTER JOIN
                      dbo.ArticoleVariante ON dbo.DocumenteDetaliu.IDVariantaArticol = dbo.ArticoleVariante.IDVariantaArticol AND 
                      dbo.Articole.IDArticol = dbo.ArticoleVariante.IDArticol LEFT OUTER JOIN
                      dbo.ArticoleParteneri ON dbo.DocumenteDetaliu.IDArticol = dbo.ArticoleParteneri.IDArticol AND dbo.Documente.IDPartener = dbo.ArticoleParteneri.IDPartener

GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Unitati' AND COLUMN_NAME = 'IDJudet')
BEGIN
	ALTER TABLE dbo.Unitati ADD IDJudet int NULL
	ALTER TABLE dbo.Unitati ADD CONSTRAINT
	FK_Unitati_Judete FOREIGN KEY
	(
	IDJudet
	) REFERENCES dbo.Judete
	(
	IDJudet
	) ON UPDATE  NO ACTION 
	 ON DELETE  NO ACTION 
END
GO


IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[fares_viewUnitati]'))
DROP VIEW [dbo].[fares_viewUnitati]
GO


CREATE VIEW [dbo].[fares_viewUnitati]
AS
SELECT     dbo.Unitati.Denumire, dbo.Unitati.CUI, dbo.Unitati.AtributFiscal, dbo.Unitati.Adresa, dbo.Unitati.IBAN, dbo.Judete.Nume, dbo.Banci.Denumire AS DenumireBanca, 
                      dbo.Unitati.Telefon, dbo.Unitati.Fax, dbo.Unitati.Reprezentant, dbo.Unitati.Email, dbo.Unitati.JudRegComert, dbo.Unitati.NrRegComert, dbo.Unitati.AnRegComert, 
                      dbo.Unitati.CodUnitate, dbo.Unitati.CapitalSocial
FROM         dbo.Unitati LEFT OUTER JOIN
                      dbo.Judete ON dbo.Unitati.IDJudet = dbo.Judete.IDJudet LEFT OUTER JOIN
                      dbo.Banci ON dbo.Unitati.IDBanca = dbo.Banci.IdBanca

GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'TipDocument' AND COLUMN_NAME = 'ModificaStoc')
BEGIN
	ALTER TABLE dbo.TipDocument ADD ModificaStoc bit NOT NULL  DEFAULT 0
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'GestiuneaStocurilor')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD GestiuneaStocurilor bit NOT NULL DEFAULT 1
END
GO

IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[fares_viewStocCurent]'))
DROP VIEW [dbo].[fares_viewStocCurent]
GO

CREATE VIEW [dbo].[fares_viewStocCurent]
AS
SELECT     s.IDArticol, s.Pret, s.IDVarinataArticol, s.IDDepartament, COALESCE (stin.Intrari, 0) AS Intrari, COALESCE (stout.Iesiri, 0) AS Iesiri, s.StocInitial, s.StocPrecedent, 
                      COALESCE (stin.Intrari, 0) - COALESCE (stout.Iesiri, 0) + s.StocInitial + s.StocPrecedent AS Stoc
FROM         dbo.Stocuri AS s LEFT OUTER JOIN
                          (SELECT     ddin.IDArticol, SUM(ddin.Cantitate) AS Intrari
                            FROM          dbo.DocumenteDetaliu AS ddin INNER JOIN
                                                   dbo.Documente AS din ON ddin.IDDocument = din.IDDocument INNER JOIN
                                                   dbo.TipDocument AS td ON din.IDTipDocument = td.IDTipDocument
                            WHERE      (td.ModificaStoc = 1) AND (td.TipOperatie LIKE '%I%')
                            GROUP BY ddin.IDArticol) AS stin ON stin.IDArticol = s.IDArticol LEFT OUTER JOIN
                          (SELECT     ddin.IDArticol, SUM(ddin.Cantitate) AS Iesiri
                            FROM          dbo.DocumenteDetaliu AS ddin INNER JOIN
                                                   dbo.Documente AS din ON ddin.IDDocument = din.IDDocument INNER JOIN
                                                   dbo.TipDocument AS td ON din.IDTipDocument = td.IDTipDocument
                            WHERE      (td.ModificaStoc = 1) AND (td.TipOperatie LIKE '%O%')
                            GROUP BY ddin.IDArticol) AS stout ON stout.IDArticol = s.IDArticol

GO

IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[fares_viewStocuri]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_viewStocuri]
GO


-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[fares_viewStocuri]
	@IDArticol int, 
	@LaData datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
		
	SELECT     s.IDArticol, s.Pret, s.IDVarinataArticol, s.IDDepartament, COALESCE (stin.Intrari, 0) AS Intrari, COALESCE (stout.Iesiri, 0) AS Iesiri, s.StocInitial, s.StocPrecedent, 
                      COALESCE (stin.Intrari, 0) - COALESCE (stout.Iesiri, 0) + s.StocInitial + s.StocPrecedent AS Stoc
	FROM         dbo.Stocuri AS s LEFT OUTER JOIN
          (SELECT     ddin.IDArticol, SUM(ddin.Cantitate) AS Intrari
            FROM          dbo.DocumenteDetaliu AS ddin INNER JOIN
                                   dbo.Documente AS din ON ddin.IDDocument = din.IDDocument INNER JOIN
                                   dbo.TipDocument AS td ON din.IDTipDocument = td.IDTipDocument
            WHERE      (td.ModificaStoc = 1) AND (td.TipOperatie LIKE '%I%' AND din.DataDoc <= @LaData AND ddin.IDArticol = @IDArticol)
            GROUP BY ddin.IDArticol) AS stin ON stin.IDArticol = s.IDArticol LEFT OUTER JOIN
          (SELECT     ddin.IDArticol, SUM(ddin.Cantitate) AS Iesiri
            FROM          dbo.DocumenteDetaliu AS ddin INNER JOIN
                                   dbo.Documente AS din ON ddin.IDDocument = din.IDDocument INNER JOIN
                                   dbo.TipDocument AS td ON din.IDTipDocument = td.IDTipDocument
            WHERE      (td.ModificaStoc = 1) AND (td.TipOperatie LIKE '%O%' AND din.DataDoc <= @LaData AND ddin.IDArticol = @IDArticol)
            GROUP BY ddin.IDArticol) AS stout ON stout.IDArticol = s.IDArticol
END

GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Stocuri' AND COLUMN_NAME = 'DataIntrare')
BEGIN
	ALTER TABLE dbo.Stocuri ADD DataIntrare datetime NOT NULL DEFAULT (GETDATE())
END
GO







IF  EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[fares_GenereazaCodArticol]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_GenereazaCodArticol]
GO

CREATE PROCEDURE [dbo].[fares_GenereazaCodArticol]
	-- Add the parameters for the stored procedure here
	@radacina varchar(10),
	@codNou varchar(20) out
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @CodReturnat varchar(20)
	DECLARE @CodReturnatNumar varchar(20)
	DECLARE @CodReturnatNumarFilt varchar(20)
	DECLARE @valNumar decimal(18,0)
	DECLARE @i int
    -- Insert statements for procedure here
	SELECT @CodReturnat=Max(codarticol) from articole where codarticol like @radacina + '%'
	--PRINT('test:[' + @CodReturnat+ ']')
	if @CodReturnat is null
	begin 
		SET @CodReturnat = @radacina + '001'
	end
	else
	begin
		SET @CodReturnat = SUBSTRING(@CodReturnat,0,10)
		--PRINT('@CodReturnat:[' + @CodReturnat+ ']')
		SET @CodReturnatNumar = REPLACE(@CodReturnat,@radacina,'')
		--PRINT('@CodReturnatNumar:[' + @CodReturnatNumar+ ']')
		SET @valNumar = 1
		SET @i = 1
		SET @CodReturnatNumarFilt = ''
		--PRINT('Inainte de while')
		WHILE @i<= LEN(@CodReturnatNumar)
		BEGIN
			IF SUBSTRING(@CodReturnatNumar,@i,1) >='0' AND SUBSTRING(@CodReturnatNumar,@i,1)<='9'
				SET @CodReturnatNumarFilt = @CodReturnatNumarFilt + SUBSTRING(@CodReturnatNumar,@i,1)
			SET @i=@i+1
		END
		
		--PRINT('@CodReturnatNumarFilt:[' + @CodReturnatNumarFilt+ ']')
		
		IF LTRIM(RTRIM(@CodReturnatNumarFilt)) <> ''
		BEGIN	
			PRINT('@CodReturnatNumarFilt:[' + @CodReturnatNumarFilt+ ']')
			
			SET @valNumar = CAST(@CodReturnatNumarFilt AS decimal(20,0))
			SET @valNumar = @valNumar + 1
		END
			
		
		--PRINT('@valNumar:[' + @valNumar+ ']')
		SET @CodReturnat = CAST(@valNumar as varchar)
		--PRINT('@CodReturnat:[' + @CodReturnat+ ']')
		SET @CodReturnat = @radacina + REPLICATE('0',3-LEN(@CodReturnat)) + @CodReturnat
		--PRINT('@CodReturnat:[' + @CodReturnat+ ']')
		WHILE EXISTS(SELECT * from articole where codarticol = @CodReturnat)
		BEGIN
			SET @valNumar = @valNumar + 1
			SET @CodReturnat = CAST(@valNumar as varchar)
			SET @CodReturnat = @radacina + REPLICATE('0',3-LEN(@CodReturnat)) + @CodReturnat
		END

	end
	SET @codNou = @CodReturnat
END

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[balcon_GenerareAnaliticeArticoleAlineate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[balcon_GenerareAnaliticeArticoleAlineate]
GO




-- =============================================
-- Author:		Dorin Popa
-- Create date: 21.05.2011
-- Description:	Genereaza analitice pentru conturile care au articole si alineate
-- =============================================
CREATE PROCEDURE [dbo].[balcon_GenerareAnaliticeArticoleAlineate] 
	-- Add the parameters for the stored procedure here
	@Cont TipCont, 
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	INSERT INTO [Conturi]
           ([Cont]
           ,[CodUnitate]
           ,[Denumire]
           ,[Tip]
           ,[Terminal]
           ,[ContParinte]
           ,[EsteAnalitic]
           ,[DebitInitial]
           ,[CreditInitial]
           ,[DebitPrecedent]
           ,[CreditPrecedent]
           ,[Categorie]
           ,[RulajDebit]
           ,[RulajCredit]
           ,[Sold])
           
     SELECT RTRIM(LTRIM(@Cont)) +'.' + RTRIM(LTRIM([ArtAl])) AS [Cont]
      ,aa.[CodUnitate]
      ,aa.[Denumire]
      ,cc.Tip
      ,aa.[Terminal]
      ,RTRIM(LTRIM(@Cont)) + CASE WHEN RTRIM(LTRIM([AAParinte]))='N/A' THEN '' ELSE '.' +RTRIM(LTRIM([AAParinte])) END  AS [ContParinte]
      ,1 AS [EsteAnalitic]
      ,0,0,0,0
      ,cc.[Categorie]
      ,0,0,0
	 FROM [ArticoleAliniate] aa JOIN [Conturi] cc ON aa.CodUnitate=cc.CodUnitate AND cc.Cont=@cont AND cc.CodUnitate=@CodUnitate
	 WHERE aa.CodUnitate = @CodUnitate AND [Categorii] like '%[CLT]%'  AND [ArtAl]<>'N/A'
	 AND NOT EXISTS(SELECT * FROM [Conturi] WHERE [CodUnitate]=@CodUnitate AND 
	 [CONT]=RTRIM(LTRIM(@Cont)) +'.' + RTRIM(LTRIM(aa.[ArtAl])))
	 
	 
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CreazaArhivaFares]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CreazaArhivaFares]
GO



CREATE PROCEDURE [dbo].[CreazaArhivaFares]
	@An smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @strTabelaAn varchar(40)
	DECLARE @Comanda varchar(8000)
	DECLARE @existTable bit
	
	SET @strTabelaAn = cast(@An AS varchar(4)) 
	SET @existTable = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE 'Documente' + @strTabelaAn)
		SET @existTable = 1
	
	--verifica existenta tabeleli arhiva
	SET @Comanda = 'CREATE TABLE [dbo].[Documente'+@strTabelaAn+'](
		[IDDocument] [bigint] NOT NULL,
		[NrDoc] [varchar](20) NOT NULL,
		[DataDoc] [datetime] NOT NULL,
		[IDPartener] [bigint] NOT NULL,
		[CodUnitate] [smallint] NOT NULL DEFAULT 0,
		[CotaTVA] [decimal](5, 2) NOT NULL DEFAULT 0,
		[IDTipDocument] [smallint] NOT NULL DEFAULT 0,
		[TotalValoare] [decimal](25, 5) NOT NULL DEFAULT 0,
		[TotalValoareTVA] [decimal](25, 5) NOT NULL DEFAULT 0,
		[Total] [decimal](25, 5) NOT NULL DEFAULT 0,
		[IDRegimFiscal] [smallint] NOT NULL DEFAULT 0,
		[UserId] [uniqueidentifier] NULL,
		[IDDepartament] [int] NULL DEFAULT 0,
		[NrContract] [varchar](50) NULL,
		[DataContract] [datetime] NULL,
		[Observatii] [varchar](250) NULL,
		[DataScadenta] [datetime] NULL,
		[ValoareTotalaCuAdaos] [decimal](25, 5) NOT NULL DEFAULT 0,
		[NrDocReceptie] [varchar](20) NULL,
		[DataDocReceptie] [datetime] NULL,
		[IDGestionar] [int] NULL,
		[IDPredator] [int] NULL,
	 CONSTRAINT [PK_Documente'+@strTabelaAn+'] PRIMARY KEY CLUSTERED 
	(
		[IDDocument] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
	 CONSTRAINT [Dublare_Documente_Furnizor_Numar_Data'+@strTabelaAn+'] UNIQUE NONCLUSTERED 
	(
		[IDPartener] ASC,
		[CodUnitate] ASC,
		[NrDoc] ASC,
		[DataDoc] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
	 CONSTRAINT [FK_Documente_Departamente'+@strTabelaAn+'] FOREIGN KEY ([IDDepartament]) REFERENCES [dbo].[Departamente] ([IDDepartament]),
	 CONSTRAINT [FK_Documente_Parteneri'+@strTabelaAn+'] FOREIGN KEY([IDPartener]) REFERENCES [dbo].[Parteneri] ([IDPartener]),
	 CONSTRAINT [FK_Documente_RegimFiscal'+@strTabelaAn+'] FOREIGN KEY([IDRegimFiscal]) REFERENCES [dbo].[RegimFiscal] ([IDRegimFiscal]),
	 CONSTRAINT [FK_Documente_TipDocument'+@strTabelaAn+'] FOREIGN KEY([IDTipDocument]) REFERENCES [dbo].[TipDocument] ([IDTipDocument]),
	 CONSTRAINT [FK_Documente_Unitati'+@strTabelaAn+'] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])
	) ON [PRIMARY]'
		
	IF @existTable = 0
		EXEC(@Comanda)
		

	SET @existTable = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE 'DocumenteDetaliu'+@strTabelaAn)
		SET @existTable = 1

	SET @Comanda = 'CREATE TABLE [dbo].[DocumenteDetaliu'+@strTabelaAn+'](
		[IDDocumentDetaliu] [bigint] NOT NULL,
		[IDDocument] [bigint] NOT NULL,
		[IDArticol] [int] NOT NULL,
		[Cantitate] [decimal](25, 5) NOT NULL DEFAULT 0,
		[ValoareUnitara] [decimal](25, 5) NOT NULL  DEFAULT 0,
		[ValoareTVA] [decimal](25, 5) NOT NULL  DEFAULT 0,
		[ValoareTotala] [decimal](25, 5) NOT NULL,
		[CodUnitate] [smallint] NOT NULL  DEFAULT 0,
		[IDUnitateMasura] [smallint] NOT NULL  DEFAULT 0,
		[IDRegimFiscal] [smallint] NOT NULL  DEFAULT 0,
		[CotaTVA] [decimal](5, 2) NOT NULL DEFAULT 0,
		[TermenLivrare] [datetime] NULL,
		[IDVariantaArticol] [int] NULL,
		[Observatii] [varchar](250) NULL,
		[ValoareTotalaCuAdaos] [decimal](25, 5) NOT NULL DEFAULT 0,
	 CONSTRAINT [PK_DocumenteDetaliu'+@strTabelaAn+'] PRIMARY KEY CLUSTERED 
	(
		[IDDocumentDetaliu] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
	CONSTRAINT [FK_DocumenteDetaliu_Articole'+@strTabelaAn+'] FOREIGN KEY([IDArticol]) REFERENCES [dbo].[Articole] ([IDArticol]),
	CONSTRAINT [FK_DocumenteDetaliu_ArticoleVariante'+@strTabelaAn+'] FOREIGN KEY([IDVariantaArticol])REFERENCES [dbo].[ArticoleVariante] ([IDVariantaArticol]),
	CONSTRAINT [FK_DocumenteDetaliu_Documente'+@strTabelaAn+'] FOREIGN KEY([IDDocument]) REFERENCES [dbo].[Documente'+@strTabelaAn+'] ([IDDocument]),
	CONSTRAINT [FK_DocumenteDetaliu_RegimFiscal'+@strTabelaAn+'] FOREIGN KEY([IDRegimFiscal]) REFERENCES [dbo].[RegimFiscal] ([IDRegimFiscal]),
	CONSTRAINT [FK_DocumenteDetaliu_Unitati'+@strTabelaAn+'] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate]),
	CONSTRAINT [FK_DocumenteDetaliu_UnitatiMasura'+@strTabelaAn+'] FOREIGN KEY([IDUnitateMasura]) REFERENCES [dbo].[UnitatiMasura] ([IDUnitateMasura])
	) ON [PRIMARY]'
	
	IF @existTable = 0
		EXEC(@Comanda)
		
	SET @existTable = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE 'DocumentePlata'+@strTabelaAn)
		SET @existTable = 1

	SET @Comanda = 'CREATE TABLE [dbo].[DocumentePlata'+@strTabelaAn+'](
		[IDDocumentPlata] [int] NOT NULL,
		[Numar] [varchar](20) NOT NULL,
		[Data] [datetime] NOT NULL,
		[IDTipPlata] [smallint] NOT NULL,
		[ValoareTotala] [decimal](18, 2) NOT NULL DEFAULT 0,
		[IDPartener] [bigint] NOT NULL,
		[Reprezentand] [varchar](250) NULL,
		[TipOperatiune] [varchar](10) NOT NULL DEFAULT (''INC''),
		[CodUnitate] [smallint] NOT NULL DEFAULT 0,
		[DataExtras] [datetime] NULL,
	 CONSTRAINT [PK_DocumentePlata'+@strTabelaAn+'] PRIMARY KEY CLUSTERED 
	(
		[IDDocumentPlata] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
	CONSTRAINT [FK_DocumentePlata'+@strTabelaAn+'_Parteneri] FOREIGN KEY([IDPartener]) REFERENCES [dbo].[Parteneri] ([IDPartener]),
	CONSTRAINT [FK_DocumentePlata'+@strTabelaAn+'_TipDocumentPlata] FOREIGN KEY([IDTipPlata]) REFERENCES [dbo].[TipDocumentPlata] ([IDTipPlata]),
	CONSTRAINT [FK_DocumentePlata'+@strTabelaAn+'_Unitati] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])
	) ON [PRIMARY]'

	IF @existTable = 0
		EXEC(@Comanda)
		
	SET @existTable = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE 'DocumentePlataDetaliu'+@strTabelaAn)
		SET @existTable = 1

	SET @Comanda = 'CREATE TABLE [dbo].[DocumentePlataDetaliu'+@strTabelaAn+'](
		[IDDocPlataDetaliu] [int] NOT NULL,
		[IDDocument] [bigint] NULL,
		[IDDocumentPlata] [int] NOT NULL,
		[Valoare] [decimal](18, 2) NOT NULL DEFAULT 0,
	 CONSTRAINT [PK_DocumentePlataDetaliu'+@strTabelaAn+'] PRIMARY KEY CLUSTERED 
	(
		[IDDocPlataDetaliu] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
		CONSTRAINT [FK_DocumentePlataDetaliu'+@strTabelaAn+'_DocumentePlata'+@strTabelaAn+'] FOREIGN KEY([IDDocumentPlata]) REFERENCES [dbo].[DocumentePlata'+@strTabelaAn+'] ([IDDocumentPlata]),
		CONSTRAINT [FK_DocumentePlataDetaliu_DocumentePlataDetaliu'+@strTabelaAn+'] FOREIGN KEY([IDDocument]) REFERENCES [dbo].[Documente'+@strTabelaAn+'] ([IDDocument])	
	) ON [PRIMARY]'

	IF @existTable = 0
			EXEC(@Comanda)
			
	SET @existTable = 0
	IF  EXISTS (SELECT * FROM sysobjects WHERE id =  OBJECT_ID(N'[dbo].[fares_DocumentePlatite'+@strTabelaAn+']'))
		SET @existTable = 1

	SET @Comanda = 'CREATE VIEW [dbo].[fares_DocumentePlatite'+@strTabelaAn+']
			AS
	SELECT     a.IDDocPlataDetaliu, a.IDDocumentPlata, a.Valoare, 
						  b.NrDoc + ''/'' + CONVERT(varchar(20), b.DataDoc, 101) AS NrDataDoc, a.IDDocument
	FROM         dbo.DocumentePlataDetaliu'+@strTabelaAn+' a INNER JOIN
						  dbo.Documente'+@strTabelaAn+'  b ON a.IDDocument = b.IDDocument'		
    IF @existTable = 0
			EXEC(@Comanda)
		
END		


GO



IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'PersoaneSuspCM' AND COLUMN_NAME = 'MotivSuspendare')
BEGIN
	ALTER TABLE dbo.PersoaneSuspCM ADD MotivSuspendare int NOT NULL DEFAULT (0)
END
GO



DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [aspnet_Applications] WHERE [LoweredApplicationName]='cabimed'
IF @Cate= 0 
BEGIN
	INSERT INTO [aspnet_Applications] ([ApplicationName],[LoweredApplicationName],[ApplicationId],[Description],[System],[IDIntern],[MenuName],[NumeDLL])VALUES('CabiMed','cabimed','E4045A52-E820-4C37-85AA-886D8591ABCD','Management Cabinete Medicale',1,'02','Consultatii','CabiMed.dll')
END



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Medicamente]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Medicamente](
	[idMedicament] [int] IDENTITY(1,1) NOT NULL,
	[denumire] [varchar](50) NOT NULL,
	[den_intern] [varchar](50) NOT NULL,
	[producator] [varchar](50) NOT NULL,
	[tara] [varchar](50) NOT NULL,
	[prezentare] [varchar](50) NOT NULL,
	[concentrat] [varchar](50) NOT NULL,
	[um] [varchar](50) NOT NULL,
	[codifatc] [varchar](50) NULL,
	[ut] [int] NULL,
	[prescri] [varchar](50) NULL,
	[forma] [varchar](50) NULL,
	[Preferat] [bit] NOT NULL DEFAULT ((0))
) ON [PRIMARY]
END
GO


IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ConfigMediCab]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ConfigMediCab](
	[idConfig] [int] IDENTITY(1,1) NOT NULL,
	[NumeFirma1] [varchar](50) NOT NULL,
	[NumeFirma2] [varchar](50) NULL,
	[Titlu1] [varchar](50) NOT NULL,
	[Titlu2] [varchar](50) NULL,
	[Adresa] [varchar](200) NOT NULL,
	[Orar] [varchar](50) NOT NULL,
 CONSTRAINT [PK_ConfigMediCab] PRIMARY KEY CLUSTERED 
(
	[idConfig] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
END
GO


/****** Object:  Table [dbo].[ConfigMediCab]    Script Date: 03/29/2012 15:23:25 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ConfigMediCab]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ConfigMediCab](
		[idConfig] [int] IDENTITY(1,1) NOT NULL,
		[NumeFirma1] [varchar](100) NOT NULL,
		[NumeFirma2] [varchar](100) NULL,
		[Titlu1] [varchar](50) NULL,
		[Titlu2] [varchar](50) NULL,
		[Adresa] [varchar](200) NULL,
		[Orar] [varchar](50) NULL,
		[Imagistica] [bit] NOT NULL DEFAULT ((0)),
		[CodUnitate] [smallint] NULL,
	 CONSTRAINT [PK_ConfigMediCab] PRIMARY KEY CLUSTERED 
	(
		[idConfig] ASC
	),
	CONSTRAINT [FK_ConfigMediCab_Unitati] FOREIGN KEY([CodUnitate])
	REFERENCES [dbo].[Unitati] ([CodUnitate])
	) ON [PRIMARY]
END
GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Consultatii]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Consultatii](
		[IdCons] [int] IDENTITY(1,1) NOT NULL,
		[IdPersoana] [int] NOT NULL,
		[Data] [datetime] NOT NULL DEFAULT (getdate()),
		[Motivele_prezentarii] [varchar](1000) NULL,
		[ExamenClinic] [varchar](500) NULL,
		[ExamenLaborator] [varchar](500) NULL,
		[Ecografie] [varchar](1000) NULL,
		[Cistoscopie] [varchar](1000) NULL,
		[Diagnostic] [varchar](2000) NULL,
		[Reteta] [varchar](3000) NULL,
		[TratamentRecomandat] [varchar](1000) NULL,
		[TratamentEfectuat] [varchar](1000) NULL,
		[AlteInformatii] [varchar](1000) NULL,
		[Anamneza] [varchar](500) NULL,
		[FactoriDeRisc] [varchar](500) NULL,
	 CONSTRAINT [PK_Consultatii] PRIMARY KEY CLUSTERED 
	(
		[IdCons] ASC
	),
	 CONSTRAINT [FK_Consultatii_Persoane] FOREIGN KEY([IdPersoana])
	REFERENCES [dbo].[Persoane] ([IdPersoana])
	) ON [PRIMARY]
END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[ListaProgramari]'))
DROP VIEW [dbo].[ListaProgramari]
GO

CREATE VIEW [dbo].[ListaProgramari]
AS
SELECT     dbo.Persoane.NumePrenume, dbo.Persoane.Cnp, dbo.ProgramareConsultatie.Ora, dbo.ProgramareConsultatie.Observatii, dbo.ProgramareConsultatie.Data
FROM         dbo.Persoane INNER JOIN
                      dbo.ProgramareConsultatie ON dbo.Persoane.IdPersoana = dbo.ProgramareConsultatie.idPersoana

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[_GenListaProgramari]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[_GenListaProgramari]
GO

CREATE PROCEDURE [dbo].[_GenListaProgramari] 
	-- Add the parameters for the stored procedure here
	@LaData datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * FROM ListaProgramari WHERE YEAR(Data) = YEAR(@ladata) AND MONTH(Data) = MONTH(@ladata) AND DAY(Data) = DAY(@ladata)
END

GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Unitati' AND COLUMN_NAME = 'CNPReprezentant')
BEGIN
	ALTER TABLE dbo.Unitati ADD CNPReprezentant decimal(13,0) NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Unitati' AND COLUMN_NAME = 'AdresaReprezentant')
BEGIN
	ALTER TABLE dbo.Unitati ADD AdresaReprezentant varchar(200) NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Unitati' AND COLUMN_NAME = 'TelefonReprezentant')
BEGIN
	ALTER TABLE dbo.Unitati ADD TelefonReprezentant varchar(20) NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Unitati' AND COLUMN_NAME = 'EmailReprezentant')
BEGIN
	ALTER TABLE dbo.Unitati ADD EmailReprezentant varchar(100) NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Unitati' AND COLUMN_NAME = 'FunctieReprezentant')
BEGIN
	ALTER TABLE dbo.Unitati ADD FunctieReprezentant varchar(100) NULL 
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'BalConSetup' AND COLUMN_NAME = 'LiniiSemnatura')
BEGIN
	ALTER TABLE dbo.BalConSetup ADD LiniiSemnatura bit DEFAULT 1 NULL
END
GO


IF  EXISTS (SELECT * FROM sysobjects WHERE id =  OBJECT_ID(N'[dbo].[CreazaArhiva]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CreazaArhiva]
GO

CREATE PROCEDURE [dbo].[CreazaArhiva]
	@An smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @strContAn varchar(40)
	DECLARE @Comanda varchar(3000)
	DECLARE @existTableCont bit
	
	SET @strContAn = 'Conturi' + cast(@An AS varchar(4)) 
	SET @existTableCont = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strContAn)
		SET @existTableCont = 1
	
	--verifica existenta tabeleli arhiva
	SET @Comanda = 'CREATE TABLE [' + @strContAn + '] (
		[Cont] [dbo].[TipCont] NOT NULL,
		[CodUnitate] [smallint] NOT NULL,
		[Denumire] [varchar](200) NOT NULL,
		[Tip] [char](1) NOT NULL,
		[Terminal] [bit] NOT NULL,
		[ContParinte] [dbo].[TipCont] NOT NULL,
		[EsteAnalitic] [bit] NOT NULL,
		[DebitInitial] [decimal](20, 2) NOT NULL,
		[CreditInitial] [decimal](20, 2) NOT NULL,
		[DebitPrecedent] [decimal](20, 2) NOT NULL,
		[CreditPrecedent] [decimal](20, 2) NOT NULL,
		[Categorie] [tinyint] NOT NULL,
		[RulajDebit] [decimal](20, 2) NOT NULL,
		[RulajCredit] [decimal](20, 2) NOT NULL,
		[Sold] [decimal](20, 2) NOT NULL,
		[SortValue] [dbo].[TipCont] NOT NULL,
	CONSTRAINT [PK_'+@strContAn +'] PRIMARY KEY CLUSTERED(
		[Cont] ASC,
		[CodUnitate] ASC
	)) ON [PRIMARY]'
	
	IF @existTableCont = 0
		EXEC(@Comanda)
		
	SET @Comanda = 'ALTER TABLE [' + @strContAn +']  WITH CHECK ADD  CONSTRAINT [FK_'+@strContAn +'_' + @strContAn + '] FOREIGN KEY([ContParinte], [CodUnitate])
		REFERENCES ['+@strContAn+'] ([Cont], [CodUnitate])'
	IF @existTableCont = 0
		EXEC(@Comanda)
		
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] CHECK CONSTRAINT [FK_'+@strContAn +'_' + @strContAn + ']'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strContAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableCont = 0
		EXEC(@Comanda)	
		
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] CHECK CONSTRAINT [FK_'+@strContAn+'_Unitati]'
	IF @existTableCont = 0
		EXEC(@Comanda)	
		
		
	SET @Comanda = 'ALTER TABLE ['+@strContAn+']  WITH NOCHECK ADD  CONSTRAINT [CK_'+@strContAn+'_Tip] CHECK  (([Tip]=''A'' OR [Tip]=''P'' OR [Tip]=''B''))'
	IF @existTableCont = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] CHECK CONSTRAINT [CK_'+@strContAn+'_Tip]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Simbol]  DEFAULT ('''') FOR [Cont]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Denumire]  DEFAULT ('''') FOR [Denumire]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Tip]  DEFAULT (''A'') FOR [Tip]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Terminal]  DEFAULT ((1)) FOR [Terminal]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_CodContParinte]  DEFAULT ('''') FOR [ContParinte]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_EsteAnalitic]  DEFAULT ((1)) FOR [EsteAnalitic]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_DebitInitial]  DEFAULT ((0)) FOR [DebitInitial]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_CreditInitial]  DEFAULT ((0)) FOR [CreditInitial]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_DebitPrecedent]  DEFAULT ((0)) FOR [DebitPrecedent]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_CreditPrecedent]  DEFAULT ((0)) FOR [CreditPrecedent]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Categorie]  DEFAULT ((0)) FOR [Categorie]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_RulajDebit]  DEFAULT ((0)) FOR [RulajDebit]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_RulajCredit]  DEFAULT ((0)) FOR [RulajCredit]'
	IF @existTableCont = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Sold]  DEFAULT ((0)) FOR [Sold]'
	IF @existTableCont = 0
		EXEC(@Comanda)	

	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_SortValue]  DEFAULT ('''') FOR [SortValue]'
	IF @existTableCont = 0
		EXEC(@Comanda)

	DECLARE @strAAAn varchar(40)
	DECLARE @existTableAA bit
	
	SET @strAAAn = 'ArticoleAliniate' + cast(@An AS varchar(4)) 
	SET @existTableAA = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strAAAn)
		SET @existTableAA = 1

	SET @Comanda = 'CREATE TABLE ['+@strAAAn+'](
	[ArtAl] [varchar](40) NOT NULL,
	[Denumire] [varchar](200) NOT NULL,
	[AAParinte] [varchar](40) NOT NULL,
	[Terminal] [bit] NOT NULL,
	[Titlu] [varchar](100) NOT NULL,
	[Categorii] [varchar](50) NOT NULL,
	[TermDenumire] [varchar](100) NOT NULL,
	[StartDenumire] [varchar](100) NOT NULL,
	[Anexa6] [bit] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	CONSTRAINT [PK_'+@strAAAn+'] PRIMARY KEY CLUSTERED(
		[ArtAl] ASC,
		[CodUnitate] ASC
	)) ON [PRIMARY]'
	IF @existTableAA = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strAAAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strAAAn+'_'+@strAAAn+'] FOREIGN KEY([AAParinte], [CodUnitate])
		REFERENCES ['+@strAAAn+'] ([ArtAl], [CodUnitate])'
	IF @existTableAA = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE [dbo].['+@strAAAn+'] CHECK CONSTRAINT [FK_'+@strAAAn+'_'+@strAAAn+']'
	IF @existTableAA = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE [dbo].['+@strAAAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strAAAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableAA = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE [dbo].['+@strAAAn+'] CHECK CONSTRAINT [FK_'+@strAAAn+'_Unitati]'
	IF @existTableAA = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE [dbo].['+@strAAAn+'] ADD  CONSTRAINT [DF_'+@strAAAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableAA = 0
		EXEC(@Comanda)

	---Bilant----------------------------
	DECLARE @strBilantAn varchar(40)
	DECLARE @existTableBilant bit
	
	SET @strBilantAn = 'Bilant' + cast(@An AS varchar(4)) 
	SET @existTableBilant = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strBilantAn)
		SET @existTableBilant = 1

	SET @Comanda = 'CREATE TABLE ['+@strBilantAn+'](
	[row] [int] NOT NULL,
	[nr_rand] [text] NOT NULL,
	[text] [text] NOT NULL,
	[codfix] [int] NOT NULL,
	[cod] [varchar](10) NOT NULL,
	[coltypei] [char](1) NOT NULL,
	[soldi] [text] NOT NULL,
	[coltypef] [char](1) NOT NULL,
	[soldf] [text] NOT NULL,
	[eval] [int] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	[Boldat] [bit] NOT NULL,
	CONSTRAINT [PK_'+@strBilantAn+'] PRIMARY KEY CLUSTERED( 
		[row] ASC)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'
	IF @existTableBilant = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strBilantAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strBilantAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableBilant = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strBilantAn+'] CHECK CONSTRAINT [FK_'+@strBilantAn+'_Unitati]'
	IF @existTableBilant = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strBilantAn+'] ADD  CONSTRAINT [DF_'+@strBilantAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableBilant = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strBilantAn+'] ADD  CONSTRAINT [DF_'+@strBilantAn+'_Boldat]  DEFAULT ((0)) FOR [Boldat]'
	IF @existTableBilant = 0
		EXEC(@Comanda)

	---Conturi Valuta--------------------
	
	DECLARE @strContValutaAn varchar(40)
	DECLARE @existTableContValuta bit
	
	SET @strContValutaAn = 'ConturiValuta' + cast(@An AS varchar(4)) 
	SET @existTableContValuta = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strContValutaAn)
		SET @existTableContValuta = 1

	SET @Comanda = 'CREATE TABLE ['+@strContValutaAn+'](
	[CodValuta] [smallint] NOT NULL,
	[Cont] [dbo].[TipCont] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	[DebitInitial] [decimal](20, 2) NOT NULL,
	[CreditInitial] [decimal](20, 2) NOT NULL,
	[DebitPrecedent] [decimal](20, 2) NOT NULL,
	[CreditPrecedent] [decimal](20, 2) NOT NULL,
	[IdJurnal] [int] NOT NULL,
	CONSTRAINT [PK_'+@strContValutaAn+'] PRIMARY KEY CLUSTERED(
	[CodValuta] ASC,
	[Cont] ASC,
	[CodUnitate] ASC,
	[IdJurnal] ASC)) ON [PRIMARY]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strContValutaAn+'_'+@strContAn+'] FOREIGN KEY([Cont], [CodUnitate])
		REFERENCES ['+@strContAn+'] ([Cont], [CodUnitate])'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] CHECK CONSTRAINT [FK_'+@strContValutaAn+'_'+@strContAn+']'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strContValutaAn+'_Jurnale] FOREIGN KEY([IdJurnal])
		REFERENCES [dbo].[Jurnale] ([IDJurnal])'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] CHECK CONSTRAINT [FK_'+@strContValutaAn+'_Jurnale]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strContValutaAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] CHECK CONSTRAINT [FK_'+@strContValutaAn+'_Unitati]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+']  WITH NOCHECK ADD  CONSTRAINT [FK_'+@strContValutaAn+'_Valuta] FOREIGN KEY([CodValuta])
		REFERENCES [dbo].[Valuta] ([CodValuta])'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] CHECK CONSTRAINT [FK_'+@strContValutaAn+'_Valuta]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_CodValuta]  DEFAULT ((0)) FOR [CodValuta]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_DebitInitial]  DEFAULT ((0)) FOR [DebitInitial]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_CreditInitial]  DEFAULT ((0)) FOR [CreditInitial]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_DebitPrecedent]  DEFAULT ((0)) FOR [DebitPrecedent]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_CreditPrecedent]  DEFAULT ((0)) FOR [CreditPrecedent]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_IdJurnal]  DEFAULT ((0)) FOR [IdJurnal]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	---Jurnale Solduri Initiale--------------------
	
	DECLARE @strJurnaleSIAn varchar(40)
	DECLARE @existTableJurnaleSI bit
	
	SET @strJurnaleSIAn = 'JurnaleSolduriInitiale' + cast(@An AS varchar(4)) 
	SET @existTableJurnaleSI = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strJurnaleSIAn)
		SET @existTableJurnaleSI = 1

	SET @Comanda = 'CREATE TABLE ['+@strJurnaleSIAn+'](
	[IDJurnal] [int] NOT NULL,
	[Cont] [dbo].[TipCont] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	[DebitInitial] [decimal](18, 2) NOT NULL,
	[CreditInital] [decimal](18, 2) NOT NULL,
	[DebitPrecedent] [decimal](20, 2) NOT NULL,
	[CreditPrecedent] [decimal](20, 2) NOT NULL,
	CONSTRAINT [PK_'+@strJurnaleSIAn+'] PRIMARY KEY CLUSTERED 
	(
	[IDJurnal] ASC,
	[Cont] ASC,
	[CodUnitate] ASC
	)) ON [PRIMARY]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strJurnaleSIAn+'_' + @strContAn + '] FOREIGN KEY([Cont], [CodUnitate])
		REFERENCES [' + @strContAn + '] ([Cont], [CodUnitate])'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] CHECK CONSTRAINT [FK_'+@strJurnaleSIAn+'_' + @strContAn + ']'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strJurnaleSIAn+'_Jurnale] FOREIGN KEY([IDJurnal])
		REFERENCES [Jurnale] ([IDJurnal])'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] CHECK CONSTRAINT [FK_'+@strJurnaleSIAn+'_Jurnale]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strJurnaleSIAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [Unitati] ([CodUnitate])'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] CHECK CONSTRAINT [FK_'+@strJurnaleSIAn+'_Unitati]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] ADD  CONSTRAINT [DF_'+@strJurnaleSIAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] ADD  CONSTRAINT [DF_'+@strJurnaleSIAn+'_DebitInitial]  DEFAULT ((0)) FOR [DebitInitial]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] ADD  CONSTRAINT [DF_'+@strJurnaleSIAn+'_DebitPrecedent]  DEFAULT ((0)) FOR [DebitPrecedent]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] ADD  CONSTRAINT [DF_'+@strJurnaleSIAn+'_CreditPrecedent]  DEFAULT ((0)) FOR [CreditPrecedent]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	---Ordonantari--------------------
	
	DECLARE @strOrdonantariAn varchar(40)
	DECLARE @existTableOrdonantari bit
	
	SET @strOrdonantariAn = 'Ordonantari' + cast(@An AS varchar(4)) 
	SET @existTableOrdonantari = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strOrdonantariAn)
		SET @existTableOrdonantari = 1

	SET @Comanda = 'CREATE TABLE ['+@strOrdonantariAn+'](
	[NrDoc] [decimal](18, 0) NOT NULL,
	[DataDoc] [datetime] NOT NULL,
	[IDFurnizor] [bigint] NOT NULL,
	[ValoareLei] [decimal](20, 2) NOT NULL,
	[IDJurnal] [int] NOT NULL,
	[Scop] [varchar](100) NOT NULL,
	[DocJust] [varchar](50) NOT NULL,
	[AngLegal] [varchar](50) NOT NULL,
	[Achitat] [bit] NOT NULL,
	[IdOrdonantare] [int] NOT NULL,
	[CodUnitate] [smallint] NOT NULL DEFAULT 0,
	[IdModPlata] [int] NOT NULL DEFAULT 1,
	[TotalDatorat] [decimal](18, 2) NOT NULL DEFAULT 0,
	[TotalAvansuri] [decimal](18, 2) NOT NULL DEFAULT 0,
	[ArtAl] [varchar](40) NOT NULL DEFAULT '''',
	[VizatCFP] [bit] NOT NULL,
	[MotivRefuz] [varchar](250) NOT NULL DEFAULT '''',
	[IDResponsabil] [int] NOT NULL DEFAULT 0,
	[DataVizaCFP] [datetime] NOT NULL DEFAULT (getdate()),
	[NrRegCFP] [varchar](20) NOT NULL DEFAULT (''FARA''),
	[IBANSursa] [varchar](24) NULL,
	[IBANDest] [varchar](24) NULL,
	CONSTRAINT [PK_'+@strOrdonantariAn+'] PRIMARY KEY CLUSTERED 
	(
		[IdOrdonantare] ASC
	),
	CONSTRAINT [FK_'+@strOrdonantariAn+'_'+@strAAAn+'] FOREIGN KEY([ArtAl], [CodUnitate]) REFERENCES ['+@strAAAn+'] ([ArtAl], [CodUnitate]),
	CONSTRAINT [FK_'+@strOrdonantariAn+'_Parteneri] FOREIGN KEY([IDfurnizor]) REFERENCES [dbo].[Parteneri] ([IdPartener]),
	CONSTRAINT [FK_'+@strOrdonantariAn+'_Jurnale] FOREIGN KEY([IDJurnal]) REFERENCES [dbo].[Jurnale] ([IDJurnal]),
	CONSTRAINT [FK_'+@strOrdonantariAn+'_ModPlata] FOREIGN KEY([IdModPlata]) REFERENCES [dbo].[ModPlata] ([IDModPlata]),
	CONSTRAINT [FK_'+@strOrdonantariAn+'_Unitati] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])	
	) ON [PRIMARY]'
	IF @existTableOrdonantari = 0
		EXEC(@Comanda)

	
	---RezultatPatrimonial--------------------
	
	DECLARE @strRezultatPatrimonialAn varchar(40)
	DECLARE @existTableRezultatPatrimonial bit
	
	SET @strRezultatPatrimonialAn = 'RezultatPatrimonial' + cast(@An AS varchar(4)) 
	SET @existTableRezultatPatrimonial = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strRezultatPatrimonialAn)
		SET @existTableRezultatPatrimonial = 1

	SET @Comanda = 'CREATE TABLE ['+@strRezultatPatrimonialAn+'](
	[row] [int] NOT NULL,
	[nr_rand] [text] NOT NULL,
	[text] [text] NOT NULL,
	[codfix] [int] NOT NULL,
	[cod] [varchar](10) NOT NULL,
	[coltypei] [char](1) NOT NULL,
	[soldi] [text] NOT NULL,
	[coltypef] [char](1) NOT NULL,
	[soldf] [text] NOT NULL,
	[eval] [int] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	[Boldat] [bit] NOT NULL,
	CONSTRAINT [PK_'+@strRezultatPatrimonialAn+'] PRIMARY KEY CLUSTERED 
	(
	[row] ASC
	)) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'
	IF @existTableRezultatPatrimonial = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRezultatPatrimonialAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strRezultatPatrimonialAn+'_Unitati] FOREIGN KEY([CodUnitate])
	REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableRezultatPatrimonial = 0
		EXEC(@Comanda)
	

	SET @Comanda = 'ALTER TABLE ['+@strRezultatPatrimonialAn+'] CHECK CONSTRAINT [FK_'+@strRezultatPatrimonialAn+'_Unitati]'
	IF @existTableRezultatPatrimonial = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRezultatPatrimonialAn+'] ADD  CONSTRAINT [DF_'+@strRezultatPatrimonialAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableRezultatPatrimonial = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRezultatPatrimonialAn+'] ADD  CONSTRAINT [DF_'+@strRezultatPatrimonialAn+'_Boldat]  DEFAULT ((0)) FOR [Boldat]'
	IF @existTableRezultatPatrimonial = 0
		EXEC(@Comanda)

	---RulajeDoc--------------------
	
	DECLARE @strRulajeDocAn varchar(40)
	DECLARE @existTableRulajeDoc bit
	
	SET @strRulajeDocAn = 'RulajeDoc' + cast(@An AS varchar(4)) 
	SET @existTableRulajeDoc = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strRulajeDocAn)
		SET @existTableRulajeDoc = 1

	SET @Comanda = 'CREATE TABLE ['+@strRulajeDocAn+'](
	[IDDocument] [bigint] NOT NULL,
	[ValoareLei] [decimal](20, 2) NOT NULL,
	[ValoareValuta] [decimal](20, 2) NOT NULL,
	[NumarDoc] [decimal](18, 0) NOT NULL,
	[DataDoc] [datetime] NOT NULL,
	[NumarNota] [varchar](50) NOT NULL,
	[TipFormula] [smallint] NOT NULL,
	[IDJurnal] [int] NULL,
	[Observatii] [varchar](200) NULL,
	[xUser] [varchar](50) NOT NULL,
	[xHost] [varchar](50) NOT NULL,
	[xDate] [datetime] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	CONSTRAINT [PK_'+@strRulajeDocAn+'] PRIMARY KEY CLUSTERED 
	(
	[IDDocument] ASC
	)) ON [PRIMARY]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+']  WITH NOCHECK ADD  CONSTRAINT [FK_'+@strRulajeDocAn+'_Jurnale] FOREIGN KEY([IDJurnal])
	REFERENCES [Jurnale] ([IDJurnal])'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] CHECK CONSTRAINT [FK_'+@strRulajeDocAn+'_Jurnale]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strRulajeDocAn+'_Unitati] FOREIGN KEY([CodUnitate])
	REFERENCES [Unitati] ([CodUnitate])'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] CHECK CONSTRAINT [FK_'+@strRulajeDocAn+'_Unitati]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+']  WITH NOCHECK ADD  CONSTRAINT [CK_'+@strRulajeDocAn+'_Tip_FORMULA] CHECK  (([TipFormula] = 3 or ([TipFormula] = 2 or ([TipFormula] = 1 or [TipFormula] = 0))))'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] CHECK CONSTRAINT [CK_'+@strRulajeDocAn+'_Tip_FORMULA]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_ValoareLei]  DEFAULT (0) FOR [ValoareLei]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_ValoareValuta]  DEFAULT (0) FOR [ValoareValuta]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_NumarDoc]  DEFAULT (0) FOR [NumarDoc]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_DataDoc]  DEFAULT (getdate()) FOR [DataDoc]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_NumarNota]  DEFAULT ('''') FOR [NumarNota]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_TipFormula]  DEFAULT (0) FOR [TipFormula]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_IDJurnal]  DEFAULT (0) FOR [IDJurnal]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_xUser]  DEFAULT (suser_sname()) FOR [xUser]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_xHost]  DEFAULT (host_name()) FOR [xHost]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_xDate]  DEFAULT (0) FOR [xDate]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	---Rulaje--------------------
	
	DECLARE @strRulajeAn varchar(40)
	DECLARE @existTableRulaje bit
	
	SET @strRulajeAn = 'Rulaje' + cast(@An AS varchar(4)) 
	SET @existTableRulaje = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strRulajeAn)
		SET @existTableRulaje = 1

	SET @Comanda = 'CREATE TABLE ['+@strRulajeAn+'](
	[CodFormula] [bigint] NOT NULL,
	[ContDebit] [dbo].[TipCont] NOT NULL,
	[ContCredit] [dbo].[TipCont] NOT NULL,
	[CodValuta] [smallint] NOT NULL,
	[IDDocument] [bigint] NOT NULL,
	[ValoareValuta] [decimal](20, 2) NOT NULL,
	[Curs] [decimal](18, 4) NOT NULL,
	[ValoareLei] [decimal](20, 2) NOT NULL,
	[DataDocJust] [datetime] NOT NULL,
	[TipDocJust] [varchar](10) NOT NULL,
	[NumarDocJust] [decimal](18, 0) NOT NULL,
	[ExplicatiiDocJust] [varchar](200) NOT NULL,
	[NrCrt] [smallint] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	CONSTRAINT [PK_'+@strRulajeAn+'] PRIMARY KEY CLUSTERED 
	(
	[CodFormula] ASC
	)) ON [PRIMARY]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strRulajeAn+'_'+@strContAn+'_Credit] FOREIGN KEY([ContCredit], [CodUnitate])
	REFERENCES ['+@strContAn+'] ([Cont], [CodUnitate])'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] CHECK CONSTRAINT [FK_'+@strRulajeAn+'_'+@strContAn+'_Credit]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)
		
	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strRulajeAn+'_'+@strContAn+'_Debit] FOREIGN KEY([ContDebit], [CodUnitate])
		REFERENCES ['+@strContAn+'] ([Cont], [CodUnitate])'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] CHECK CONSTRAINT [FK_'+@strRulajeAn+'_'+@strContAn+'_Debit]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+']  WITH NOCHECK ADD  CONSTRAINT [FK_'+@strRulajeAn+'_'+@strRulajeDocAn+'] FOREIGN KEY([IDDocument])
		REFERENCES ['+@strRulajeDocAn+'] ([IDDocument])
		ON UPDATE CASCADE
		ON DELETE CASCADE'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] CHECK CONSTRAINT [FK_'+@strRulajeAn+'_'+@strRulajeDocAn+']'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strRulajeAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] CHECK CONSTRAINT [FK_'+@strRulajeAn+'_Unitati]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+']  WITH NOCHECK ADD  CONSTRAINT [FK_'+@strRulajeAn+'_Valuta] FOREIGN KEY([CodValuta])
	REFERENCES [dbo].[Valuta] ([CodValuta])'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] CHECK CONSTRAINT [FK_'+@strRulajeAn+'_Valuta]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_CodValuta]  DEFAULT (0) FOR [CodValuta]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_ValareaValuta]  DEFAULT (0) FOR [ValoareValuta]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_Curs]  DEFAULT (1) FOR [Curs]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_ValoareLei]  DEFAULT (0) FOR [ValoareLei]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_TipDocJust]  DEFAULT (''NC'') FOR [TipDocJust]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_NrCrt]  DEFAULT (1) FOR [NrCrt]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)
		
	---VenituriSiCheltuieli--------------------
	
	DECLARE @strVenituriSiCheltuieliAn varchar(40)
	DECLARE @existTableVenituriSiCheltuieli bit
	
	SET @strVenituriSiCheltuieliAn = 'VenituriSiCheltuieli' + cast(@An AS varchar(4)) 
	SET @existTableVenituriSiCheltuieli = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strVenituriSiCheltuieliAn)
		SET @existTableVenituriSiCheltuieli = 1

	SET @Comanda = 'CREATE TABLE ['+@strVenituriSiCheltuieliAn+'](
	[row] [int] NOT NULL,
	[nr_rand] [text] NOT NULL,
	[text] [text] NOT NULL,
	[codfix] [int] NOT NULL,
	[cod] [varchar](20) NOT NULL,
	[coltypei] [char](1) NOT NULL,
	[soldi] [text] NOT NULL,
	[coltypef] [char](1) NOT NULL,
	[soldf] [text] NOT NULL,
	[eval] [int] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	[Boldat] [bit] NOT NULL,
	CONSTRAINT [PK_'+@strVenituriSiCheltuieliAn+'] PRIMARY KEY CLUSTERED 
	(
	[row] ASC
	)) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'
	IF @existTableVenituriSiCheltuieli = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strVenituriSiCheltuieliAn+'] ADD  CONSTRAINT [DF_'+@strVenituriSiCheltuieliAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableVenituriSiCheltuieli = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strVenituriSiCheltuieliAn+'] ADD  CONSTRAINT [DF_'+@strVenituriSiCheltuieliAn+'_Boldat]  DEFAULT ((0)) FOR [Boldat]'
	IF @existTableVenituriSiCheltuieli = 0
		EXEC(@Comanda)
		

END
GO
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Conturi2011')
BEGIN
	IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Conturi2011' AND COLUMN_NAME = 'SortValue')
	BEGIN
	ALTER TABLE dbo.Conturi2011 DROP COLUMN SortValue
	END


	IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Conturi2011' AND COLUMN_NAME = 'Sold')
	BEGIN
		ALTER TABLE dbo.Conturi2011 ADD Sold  DECIMAL(18,2) NOT NULL DEFAULT(0)
	END
END
GO


IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Conturi2011')
BEGIN
	IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Conturi2011' AND COLUMN_NAME = 'SortValue')
	BEGIN
		ALTER TABLE dbo.Conturi2011 ADD SortValue  AS ([dbo].[GetOrderString]([Cont]))
	END
END
GO

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Semnaturi]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Semnaturi](
		[IdSemnatura] [smallint] IDENTITY(1,1) NOT NULL,
		[Nume] [varchar](100) NOT NULL,
		[Functia] [varchar](50) NOT NULL,
		[Rand] [smallint] NOT NULL DEFAULT ((0)),
		[Coloana] [smallint] NOT NULL DEFAULT ((0)),
		[System] [bit] NOT NULL DEFAULT ((0)) ,
		[LaComanda] [bit] NOT NULL DEFAULT ((1)),
		[LaReceptie] [bit] NOT NULL DEFAULT ((1)),
	 CONSTRAINT [PK_Semnaturi] PRIMARY KEY CLUSTERED 
	(
		[IdSemnatura] ASC
	)
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[admin_Liste]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[admin_Liste](
		[IDLista] [smallint] IDENTITY(1,1) NOT NULL,
		[Denumire] [varchar](50) NOT NULL,
		[Titlu] [varchar](150) NOT NULL,
	 CONSTRAINT [PK_admin_Liste] PRIMARY KEY CLUSTERED 
	(
		[IDLista] ASC
	) ON [PRIMARY]
	) ON [PRIMARY]

	SET IDENTITY_INSERT [admin_Liste] ON
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(1,'Balanta','Balanta')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(2,'Fisa contului','Fisa contului')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(3,'Cartea mare','Cartea mare')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(4,'Registrul jurnal','Registrul jurnal')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(5,'Registrul de casa','Registrul de casa')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(6,'Extras de cont','Extras de cont')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(7,'Fise generale','Fise generale')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(8,'Bilant','Bilant')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(9,'Contul de profit si pierdere','Contul de profit si pierdere')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(10,'Operatiuni diverse','Operatiuni diverse')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(11,'Extras de cont centralizat','Extras de cont centralizat')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(12,'Lista operatiunilor bugetare','Lista operatiunilor bugetare')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(13,'Executia cheltuielilor','Executia cheltuielilor')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(14,'Cont de rezultat patrimonial','Cont de rezultat patrimonial')
	INSERT INTO [admin_liste] ([IDLista],[Denumire],[Titlu])VALUES(15,'Situatia veniturilor si cheltuielilor','Situatia veniturilor si cheltuielilor')
	SET IDENTITY_INSERT [admin_Liste] OFF
END
GO


IF  NOT EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[SemnaturiListe]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[SemnaturiListe](
		[IDLista] [smallint] NOT NULL,
		[IDSemnatura] [smallint] NOT NULL,
		[TipLista] [smallint] NOT NULL,
	 CONSTRAINT [PK_SemnaturiListe] PRIMARY KEY CLUSTERED 
	(
		[IDLista] ASC,
		[IDSemnatura] ASC,
		[TipLista] ASC
	) ON [PRIMARY],
	CONSTRAINT [FK_SemnaturiListe_Semnaturi] FOREIGN KEY([IDSemnatura])  REFERENCES [dbo].[Semnaturi] ([IdSemnatura]),
	CONSTRAINT [FK_admin_Liste_Semnaturi] FOREIGN KEY([IDLista])  REFERENCES [dbo].[admin_Liste] ([IdLista])
	) ON [PRIMARY]
END


GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportFisaPartenerului]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportFisaPartenerului]
GO


CREATE PROCEDURE [dbo].[fares_FiltreazaRaportFisaPartenerului] 
	@data2 varchar(20),
	@filtru varchar(5000),
	@orderby varchar(1000)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DECLARE @sel varchar(5000)
	SET @sel = 'SELECT * FROM [fares_FisaPartenerului] WHERE ' + @filtru +
	 ' AND [DataDoc]<=''' + @data2 +''' ORDER BY ' + @orderby
	EXEC(@sel)
END

GO


DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='8489910A-6599-436A-B3E5-21B6DB74A7BE'
IF @Cate<> 0 
begin
	DELETE FROM [admin_ApplicationMenu] WHERE [ApplicationId] = '8489910A-6599-436A-B3E5-21B6DB74A7BE'
end 
go

SET IDENTITY_INSERT [admin_ApplicationMenu] ON
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2082,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Buget',NULL,10,'Buget',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2083,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Angajament Bugetar',NULL,15,'AB',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2084,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Angajament Legal',NULL,20,'AL',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2085,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Propunere Angajare Cheltuiala',NULL,14,'PAC',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2086,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Ordonantare',NULL,24,'Ordonantari',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2090,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Executia Cheltuielilor',NULL,25,'Executia_Cheltuielilor',NULL,NULL)

INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2087,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Liste',NULL,26,NULL,NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2088,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Setari',NULL,30,NULL,NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2089,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Parametrizare modul',2088,100,'Parametrizare',NULL,NULL)

INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2689,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Registrul proiectelor de operatiuni',2087,205,'Registrul_Proiecte',NULL,NULL)

INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2589,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Articole,Alineate',2088,105,'ArtAl',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2590,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Capitole',2088,110,'Jurnale',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2591,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Parteneri',2088,115,'Furnizori',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2592,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Responsabili CFP',2088,120,'ResponsabilCFP',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2593,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Banci',2088,125,'Banci',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2594,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Departamente',2088,130,'Departamente',NULL,NULL)

SET IDENTITY_INSERT [admin_ApplicationMenu] OFF	
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Departamente' AND COLUMN_NAME = 'Suprafata')
BEGIN
	ALTER TABLE dbo.departamente ADD Suprafata  DECIMAL(10,2) NULL DEFAULT(0)
END
GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArticoleAliniateCheltuieli]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ArticoleAliniateCheltuieli](
		[ArtAl] [varchar](40) NOT NULL,
		[CodUnitate] [smallint] NOT NULL,
		[Cheltuieli] [bit] NOT NULL DEFAULT(0),
	 CONSTRAINT [PK_ArticoleAliniateCheltuieli] PRIMARY KEY CLUSTERED 
	(
		[ArtAl] ASC,
		[CodUnitate] ASC
	)
	) ON [PRIMARY]
END
GO



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CheltuieliCentralizator]') AND type in (N'U'))
BEGIN
	
	CREATE TABLE [dbo].[CheltuieliCentralizator](
		[Data] [datetime] NOT NULL,
		[IDDepartament] [int] NOT NULL,
		[ArtAl] [varchar](40) NOT NULL,
		[CodUnitate] [smallint] NOT NULL,
		[Suma] [decimal](18, 2) NOT NULL DEFAULT ((0)),
		[ArtAlParinte] [varchar](40) NOT NULL DEFAULT ('N/A'),
	 CONSTRAINT [PK_CheltuieliCentralizator] PRIMARY KEY CLUSTERED 
	(
		[Data] ASC,
		[IDDepartament] ASC,
		[ArtAl] ASC,
		[CodUnitate] ASC
	),
	CONSTRAINT [FK_CheltuieliCentralizator_ArticoleAliniate] FOREIGN KEY([ArtAl], [CodUnitate])
		REFERENCES [dbo].[ArticoleAliniate] ([ArtAl], [CodUnitate]),
	CONSTRAINT [FK_CheltuieliCentralizator_Departamente] FOREIGN KEY([IDDepartament])
		REFERENCES [dbo].[Departamente] ([IDDepartament]),
	CONSTRAINT [FK_CheltuieliCentralizator_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [dbo].[Unitati] ([CodUnitate])
	) ON [PRIMARY]

END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Unitati' AND COLUMN_NAME = 'CapitalSocial')
BEGIN
	ALTER TABLE dbo.Unitati ADD CapitalSocial int NULL DEFAULT (0)
END
GO


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewDetaliuPlata]'))
DROP VIEW [dbo].[fares_viewDetaliuPlata]
GO

CREATE VIEW [dbo].[fares_viewDetaliuPlata]
AS
SELECT     dbo.DocumentePlataDetaliu.IDDocPlataDetaliu, dbo.Documente.NrDoc, dbo.Documente.DataDoc, dbo.DocumentePlataDetaliu.IDDocumentPlata
FROM         dbo.DocumentePlataDetaliu LEFT OUTER JOIN
                      dbo.Documente ON dbo.DocumentePlataDetaliu.IDDocument = dbo.Documente.IDDocument


GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Radiografii]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Radiografii](
		[IdRadiografie] [int] IDENTITY(1,1) NOT NULL,
		[IdCons] [int] NOT NULL,
		[Cale_imagine] [varchar](1000) NOT NULL,
	 CONSTRAINT [PK_Radiografii] PRIMARY KEY CLUSTERED 
	(
		[IdRadiografie] ASC
	)
	) ON [PRIMARY]
END 
GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ParamExUr]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ParamExUr](
		[IdParam] [int] NOT NULL,
		[IdCons] [int] NOT NULL,
		[Denumire] [varchar](50) NOT NULL DEFAULT(''),
		[Valoare] [varchar](500) NOT NULL DEFAULT ((0)),
		[Pozitie] [smallint] NOT NULL,
	 CONSTRAINT [PK_ParamExUr] PRIMARY KEY CLUSTERED 
	(
		[IdParam] ASC,
		[IdCons] ASC
	),
	CONSTRAINT [FK_ParamExUr_Consultatii] FOREIGN KEY([IdCons])
	REFERENCES [dbo].[Consultatii] ([IdCons]),
	CONSTRAINT [FK_ParamExUr_ParamExUrModel] FOREIGN KEY([IdParam])
	REFERENCES [dbo].[ParamExUrModel] ([IdParam])
	) ON [PRIMARY]

END
GO

/****** Object:  Table [dbo].[ParamExUrModel]    Script Date: 06/14/2012 13:01:50 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ParamExUrModel]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ParamExUrModel](
	[IdParam] [int] IDENTITY(1,1) NOT NULL,
	[Denumire] [varchar](50) NOT NULL,
	[Valoare] [varchar](500) NOT NULL DEFAULT (''),
	[Tip] [smallint] NOT NULL DEFAULT ((0)),
	[ValoareMinima] [varchar](500) NOT NULL DEFAULT ('') ,
	[ValoareMaxima] [varchar](500) NOT NULL DEFAULT (''),
	[Pozitie] [smallint] NOT NULL  DEFAULT ((0)),
 CONSTRAINT [PK_ParamExUrModel] PRIMARY KEY CLUSTERED 
(
	[IdParam] ASC
)
) ON [PRIMARY]
END
GO


/****** Object:  Table [dbo].[eDocumentPage]    Script Date: 06/18/2012 20:58:54 ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[eDocumentPage]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[eDocumentPage](
	[IDPage] [bigint] IDENTITY(1,1) NOT NULL,
	[IDDocument] [bigint] NOT NULL,
	[Titlu] [varchar](50) NOT NULL,
	[Descriere] [varchar](100) NOT NULL,
	[NrPagina] [smallint] NOT NULL DEFAULT ((0)),
	[Continut] [image] NOT NULL,
	[Data] [datetime] NOT NULL DEFAULT (getdate())
	CONSTRAINT [PK_eDocumentPage] PRIMARY KEY CLUSTERED 
	(
		[IDPage] ASC
	),
	CONSTRAINT [FK_eDocumentPage_eDocumente] FOREIGN KEY([IDDocument]) REFERENCES [dbo].[eDocumente] ([IDDocument])

) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

END 
GO

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='E03B2883-43E3-41B7-A41E-A620126D1BE0' AND [IDMeniuAplicatie]=1164

IF @Cate = 0 
begin
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1164,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Tipuri Documente Scanate',1055,26,'Tipuri_Documente_Scanate',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='E03B2883-43E3-41B7-A41E-A620126D1BE0' AND [IDMeniuAplicatie]=1065

IF @Cate = 0 
begin
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1065,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Documente Scanate',null,60,'Scanare_Documente',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 


go


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[eDocumentTip]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[eDocumentTip](
		[IDTipDocument] [int] IDENTITY(1,1) NOT NULL,
		[Denumire] [varchar](50) NOT NULL,
	 CONSTRAINT [PK_eDocumentTip] PRIMARY KEY CLUSTERED 
	(
		[IDTipDocument] ASC
	)
) ON [PRIMARY]
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'eDocumente' AND COLUMN_NAME = 'IDTipDocument')
BEGIN
	ALTER TABLE dbo.eDocumente ADD IDTipDocument int NULL 
	ALTER TABLE dbo.eDocumente ADD CONSTRAINT
		FK_eDocumente_eDocumentTip FOREIGN KEY
		(
		IDTipDocument
		) REFERENCES dbo.eDocumentTip
		(
		IDTipDocument
		) ON UPDATE  NO ACTION 
		 ON DELETE  NO ACTION 
END	
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'eDocumente' AND COLUMN_NAME = 'Copie')
BEGIN
	ALTER TABLE dbo.eDocumente ADD Copie bit NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'eDocumente' AND COLUMN_NAME = 'NrDoc')
BEGIN
	ALTER TABLE dbo.eDocumente ADD NrDoc varchar(50) NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'eDocumente' AND COLUMN_NAME = 'DataDoc')
BEGIN
	ALTER TABLE dbo.eDocumente ADD DataDoc datetime NULL 
END
GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[eDocumentPersoana]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[eDocumentPersoana](
	[IDDocPers] [int] IDENTITY(1,1) NOT NULL,
	[IDDocument] [bigint] NOT NULL,
	[IdPersoana] [int] NOT NULL,
 CONSTRAINT [PK_eDocumentPersoana] PRIMARY KEY CLUSTERED 
(
	[IDDocPers] ASC
),
CONSTRAINT [FK_eDocumentPersoana_eDocumentPersoana] FOREIGN KEY([IDDocument]) REFERENCES [dbo].[eDocumente] ([IDDocument]),
CONSTRAINT [FK_eDocumentPersoana_Persoane] FOREIGN KEY([IdPersoana]) REFERENCES [dbo].[Persoane] ([IdPersoana])
) ON [PRIMARY]
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Persoane' AND COLUMN_NAME = 'DataVechimeMunca')
BEGIN
	ALTER TABLE dbo.Persoane ADD DataVechimeMunca datetime NOT NULL  DEFAULT(getdate())
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Persoane' AND COLUMN_NAME = 'IdCasaAsigSanatate')
BEGIN
	ALTER TABLE dbo.Persoane ADD IdCasaAsigSanatate smallint NOT NULL  DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Persoane' AND COLUMN_NAME = 'Marca')
BEGIN
	ALTER TABLE dbo.Persoane ADD Marca varchar(20) NOT NULL  DEFAULT('FARA')
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Persoane' AND COLUMN_NAME = 'TelefonInterior')
BEGIN
	ALTER TABLE dbo.Persoane ADD TelefonInterior varchar(20) NULL
END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[resuma_eDocumentePersoana]'))
DROP VIEW [dbo].[resuma_eDocumentePersoana]
GO

CREATE VIEW [dbo].[resuma_eDocumentePersoana]
AS
SELECT     dbo.eDocumentPersoana.IdPersoana, dbo.eDocumente.*
FROM         dbo.eDocumente INNER JOIN
                      dbo.eDocumentPersoana ON dbo.eDocumente.IDDocument = dbo.eDocumentPersoana.IDDocument

GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ResUmaSetup' AND COLUMN_NAME = 'ScanRes')
BEGIN
	ALTER TABLE dbo.ResUmaSetup ADD ScanRes int NULL
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ResUmaSetup' AND COLUMN_NAME = 'OrizExtent')
BEGIN
	ALTER TABLE dbo.ResUmaSetup ADD OrizExtent int NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ResUmaSetup' AND COLUMN_NAME = 'VertExtent')
BEGIN
	ALTER TABLE dbo.ResUmaSetup ADD VertExtent int NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ResUmaSetup' AND COLUMN_NAME = 'ProcentCASAngajator')
BEGIN
	ALTER TABLE dbo.ResUmaSetup ADD
	[ProcentCASAngajator] [decimal](5, 2) NOT NULL  DEFAULT(0),
	[SalarMinim] [decimal](18, 0) NOT NULL DEFAULT(0),
	[SalarMediubrut] [decimal](18, 0) NOT NULL DEFAULT(0),
	[NrSalariiMaxCAS] [decimal](5, 2) NOT NULL DEFAULT(0),
	[ProcentCASAngajat] [decimal](5, 2) NOT NULL DEFAULT(0),
	[PlafonareCAS] [bit] NOT NULL DEFAULT(1),
	[ProcentSomajAngajat] [decimal](5, 2) NOT NULL DEFAULT(0),
	[ProcentSomajAngajator] [decimal](5, 2) NOT NULL DEFAULT(0),
	[ProcentASSAngajat] [decimal](5, 2) NOT NULL DEFAULT(0),
	[ProcentASSAngajator] [decimal](5, 2) NOT NULL DEFAULT(0)
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ResUmaSetup' AND COLUMN_NAME = 'ColorFormat')
BEGIN
	ALTER TABLE dbo.ResUmaSetup ADD ColorFormat int NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ResUmaSetup' AND COLUMN_NAME = 'ScanDebug')
BEGIN
	ALTER TABLE dbo.ResUmaSetup ADD ScanDebug bit NULL
END
GO


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_DocumenteTVADimensiuni]'))
DROP VIEW [dbo].[fares_DocumenteTVADimensiuni]
GO

CREATE VIEW [dbo].[fares_DocumenteTVADimensiuni]
AS
SELECT     a.IDDocument, a.NrDoc, a.DataDoc, a.CodUnitate, a.IDTipDocument, a.NrContract, a.DataContract, a.Observatii, a.DataScadenta, a.NrDocReceptie, a.DataDocReceptie, 
                      dbo.TipDocument.TipOperatie, dbo.TipDocument.Denumire, c.valoare1, c.valoare2, c.valoare3, c.valoare4, p.Denumire AS DenPartener, 
                      CASE WHEN dd.CotaTVA = 24 THEN dd.ValoareTVA ELSE 0 END AS ValoareTVA24, CASE WHEN dd.CotaTVA = 9 THEN dd.ValoareTVA ELSE 0 END AS ValoareTVA9, 
                      CASE WHEN dd.CotaTVA = 24 THEN CASE WHEN a.IDTipDocument IN (10, 11) 
                      THEN dd.ValoareTotala - dd.ValoareTVA ELSE dd.ValoareTotala END ELSE 0 END AS ValoareTotala24, 
                      CASE WHEN dd.CotaTVA = 9 THEN CASE WHEN a.IDTipDocument IN (10, 11) 
                      THEN dd.ValoareTotala - dd.ValoareTVA ELSE dd.ValoareTotala END ELSE 0 END AS ValoareTotala9, 
                      CASE WHEN dd.CotaTVA = 0 THEN CASE WHEN a.IDTipDocument IN (10, 11) 
                      THEN dd.ValoareTotala - dd.ValoareTVA ELSE dd.ValoareTotala END ELSE 0 END AS ValoareTotalaScutit, dd.CotaTVA, CASE WHEN (dd.CotaTVA = 24 OR
                      dd.CotaTVA = 0) THEN dd.ValoareTotalaCuAdaos ELSE 0 END AS ValoareTotalaCuAdaos24, 
                      CASE WHEN dd.CotaTVA = 9 THEN dd.ValoareTotalaCuAdaos ELSE 0 END AS ValoareTotalaCuAdaos9, 
                      CASE WHEN dd.CotaTVA = 0 THEN (dd.ValoareTotalaCuAdaos * 100) / (s.CotaTVAImplicita + 100) - dd.ValoareTotala ELSE CASE WHEN a.IDTipDocument IN (10, 11) 
                      THEN (dd.ValoareTotalaCuAdaos * 100) / (dd.CotaTVA + 100) - (dd.ValoareTotala * 100) / (dd.CotaTVA + 100) ELSE (dd.ValoareTotalaCuAdaos * 100) / (dd.CotaTVA + 100) 
                      - dd.ValoareTotala END END AS Adaos, CASE WHEN dd.CotaTVA = 0 THEN (dd.ValoareTotalaCuAdaos * s.CotaTVAImplicita) / (s.CotaTVAImplicita + 100) 
                      ELSE (dd.ValoareTotalaCuAdaos * dd.CotaTVA) / (dd.CotaTVA + 100) END AS TVANeexigibil, ar.Denumire AS DenArticol, p.IDPartener, ar.IDArticol
FROM         dbo.Documente AS a INNER JOIN
                      dbo.Parteneri AS p ON a.IDPartener = p.IDPartener INNER JOIN
                      dbo.TipDocument ON a.IDTipDocument = dbo.TipDocument.IDTipDocument LEFT OUTER JOIN
                      dbo.fares_DocumenteDimensiuniLinie AS c ON a.IDDocument = c.IDCheieTabela AND a.CodUnitate = c.CodUnitate INNER JOIN
                      dbo.DocumenteDetaliu AS dd ON a.IDDocument = dd.IDDocument INNER JOIN
                      dbo.Articole AS ar ON dd.IDArticol = ar.IDArticol INNER JOIN
                      dbo.FaresSetup AS s ON a.CodUnitate = s.CodUnitate
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportDocumenteTVA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportDocumenteTVA]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaRaportDocumenteTVA] 
	-- Add the parameters for the stored procedure here
	@data1 varchar(20),
	@data2 varchar(20),
	@filtru varchar(1000)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DECLARE @sel varchar(3000)
	SET @sel = 'SELECT * FROM [fares_DocumenteTVADimensiuni] WHERE ' + @filtru +
	 ' AND [DataDoc]>=''' + @data1 + ''' AND [DataDoc]<=''' + @data2 +''' ORDER BY [DataDoc]'
	EXEC(@sel)
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'Bugetara')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD Bugetara bit NOT NULL DEFAULT 0
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'ArtAl')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu ADD ArtAl varchar(40) NULL 
END
GO


IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_DocumenteDetaliu_ArticoleAliniate]') AND parent_object_id = OBJECT_ID(N'[dbo].[DocumenteDetaliu]'))
ALTER TABLE [dbo].[DocumenteDetaliu] DROP CONSTRAINT [FK_DocumenteDetaliu_ArticoleAliniate]
GO

ALTER TABLE [dbo].[DocumenteDetaliu]  WITH CHECK ADD  CONSTRAINT [FK_DocumenteDetaliu_ArticoleAliniate] FOREIGN KEY([ArtAl], [CodUnitate])
REFERENCES [dbo].[ArticoleAliniate] ([ArtAl], [CodUnitate])
GO

ALTER TABLE [dbo].[DocumenteDetaliu] CHECK CONSTRAINT [FK_DocumenteDetaliu_ArticoleAliniate]
GO

UPDATE [aspnet_Membership]
   SET [IsApproved] = 1,[UserIDUpdate] = 'ABAAB44E-53BB-4D15-904C-E79F62133F7C',[IsLockedOut]=0
GO



IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'IDJurnal')
BEGIN
ALTER TABLE dbo.Documente ADD
	IDJurnal int NULL

ALTER TABLE dbo.Documente ADD CONSTRAINT
	FK_Documente_Jurnale FOREIGN KEY
	(
	IDJurnal
	) REFERENCES dbo.Jurnale
	(
	IDJurnal
	) ON UPDATE  NO ACTION 
	 ON DELETE  NO ACTION 
	
END
go


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'ValoareUnitaraValuta')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu ADD ValoareUnitaraValuta decimal(25,5) NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'ArtAl')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu ADD ArtAl varchar(40) NULL 
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'IDJurnal')
BEGIN
ALTER TABLE dbo.Documente ADD
	IDJurnal int NULL

ALTER TABLE dbo.Documente ADD CONSTRAINT
	FK_Documente_Jurnale FOREIGN KEY
	(
	IDJurnal
	) REFERENCES dbo.Jurnale
	(
	IDJurnal
	) 	
END
go

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'CursValutar')
BEGIN
	ALTER TABLE dbo.Documente ADD CursValutar decimal(18,4) NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'CodValuta')
BEGIN
	ALTER TABLE dbo.Documente ADD CodValuta smallint NOT NULL DEFAULT 0

	ALTER TABLE [dbo].Documente  WITH CHECK ADD  CONSTRAINT [FK_Documente_Valuta] FOREIGN KEY([CodValuta]) REFERENCES [dbo].[Valuta] ([CodValuta])
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'AreDocGestStoc')
BEGIN
	ALTER TABLE dbo.Documente ADD AreDocGestStoc bit NOT NULL DEFAULT 1
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'DataStartProductie')
BEGIN
	ALTER TABLE dbo.Documente ADD DataStartProductie DateTime NOT NULL DEFAULT (getdate())
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'Valuta')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD Valuta bit NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Valuta' AND COLUMN_NAME = 'Utilizat')
BEGIN
	ALTER TABLE dbo.Valuta ADD Utilizat bit NOT NULL DEFAULT 0
END
GO

/****** Object:  Table [dbo].[ValutaCurs]    Script Date: 07/22/2012 15:39:29 ******/
IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ValutaCurs]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ValutaCurs](
		[IDCursValutar] [int] IDENTITY(1,1) NOT NULL,
		[CodValuta] [smallint] NOT NULL,
		[Data] [datetime] NOT NULL,
		[ValoareLei] [float] NOT NULL DEFAULT ((0)),
		CONSTRAINT [PK_ValutaCurs] PRIMARY KEY CLUSTERED ([IDCursValutar] ASC),
		CONSTRAINT [FK_ValutaCurs_Valuta] FOREIGN KEY([CodValuta]) REFERENCES [dbo].[Valuta] ([CodValuta]) 
	) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX [IX_ValutaDataCurs] ON [dbo].[ValutaCurs] 
	(
		[CodValuta] ASC,
		[Data] ASC
	)
END
GO

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9' and [HandlerName]='Curs_Valutar'
IF @Cate= 0 
begin
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(3414,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Curs Valutar',3400,33,'Curs_Valutar',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 
go

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'JurnalImplicit')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD JurnalImplicit int NULL DEFAULT 0

	ALTER TABLE [dbo].[FaresSetup]  WITH CHECK ADD CONSTRAINT [FK_FaresSetup_Jurnale] FOREIGN KEY([JurnalImplicit]) REFERENCES [dbo].[Jurnale] ([IDJurnal])
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'ArtAlImplicit')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD ArtAlImplicit varchar(40) NULL

	ALTER TABLE [dbo].[FaresSetup]  WITH CHECK ADD  CONSTRAINT [FK_FaresSetup_ArtAl] FOREIGN KEY([CodUnitate],[ArtAlImplicit]) REFERENCES [dbo].[ArticoleAliniate] ([CodUnitate],[ArtAl])

END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Articole' AND COLUMN_NAME = 'ArtAl')
BEGIN
	ALTER TABLE dbo.Articole ADD ArtAl varchar(40) NULL
	ALTER TABLE [dbo].Articole  WITH CHECK ADD  CONSTRAINT [FK_Articole_ArticoleAliniate] FOREIGN KEY([ArtAl],[CodUnitate]) REFERENCES [dbo].[ArticoleAliniate] ([ArtAl],[CodUnitate])

END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Articole' AND COLUMN_NAME = 'PretVanzareValuta')
BEGIN
	ALTER TABLE dbo.Articole ADD PretVanzareValuta decimal(18,4) NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Articole' AND COLUMN_NAME = 'PretVanzareCodValuta')
BEGIN
	ALTER TABLE dbo.Articole ADD PretVanzareCodValuta smallint NOT NULL DEFAULT 0

	ALTER TABLE [dbo].Articole  WITH CHECK ADD  CONSTRAINT [FK_Articole_Valuta] FOREIGN KEY([PretVanzareCodValuta]) REFERENCES [dbo].[Valuta] ([CodValuta])
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Articole' AND COLUMN_NAME = 'MateriePrima')
BEGIN
	ALTER TABLE dbo.Articole ADD MateriePrima bit NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'ValutaImplicita')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD ValutaImplicita smallint NOT NULL DEFAULT 0

	ALTER TABLE [dbo].FaresSetup  WITH CHECK ADD  CONSTRAINT [FK_FaresSetul_Valuta] FOREIGN KEY([ValutaImplicita]) REFERENCES [dbo].[Valuta] ([CodValuta])

END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'FolosesteTVAArticol')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD FolosesteTVAArticol bit NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumentePlata' AND COLUMN_NAME = 'IDOrdonantare')
BEGIN
	ALTER TABLE dbo.DocumentePlata ADD IDOrdonantare int NULL 

	ALTER TABLE [dbo].DocumentePlata  WITH CHECK ADD  CONSTRAINT [FK_DocumentePlata_Ordonantare] FOREIGN KEY([IDOrdonantare]) REFERENCES [dbo].[Ordonantari] ([IDOrdonantare])
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Ordonantari' AND COLUMN_NAME = 'IDDocumentPlata')
BEGIN
	ALTER TABLE dbo.Ordonantari ADD IDDocumentPlata int NULL 

	ALTER TABLE [dbo].Ordonantari  WITH CHECK ADD  CONSTRAINT [FK_Ordonantare_DocumentePlata] FOREIGN KEY([IDDocumentPlata]) REFERENCES [dbo].[DocumentePlata] ([IDDocumentPlata])
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GenOrdonantariPlata]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GenOrdonantariPlata]
GO


CREATE PROCEDURE [dbo].[GenOrdonantariPlata]   
@idPlata int,
@idOrdonantare int OUTPUT 
AS

DECLARE @cate int

SELECT @cate = COUNT(*) FROM DocumentePlata dp WHERE dp.IDDocumentPlata=@idPlata AND dp.IDOrdonantare is not null
IF @cate<>0
BEGIN
	PRINT('Ordonontare generata')
	UPDATE [DocumentePlata] SET IDOrdonantare = null WHERE IDDocumentPlata = @idPlata
	IF @@ERROR != 0 GOTO EROARE2				
	
	DELETE FROM [Ordonantari] WHERE IDDocumentPlata = @idPlata
	IF @@ERROR != 0 GOTO EROARE2				
END


SELECT @cate = COUNT(*) FROM DocumentePlata dp WHERE dp.IDDocumentPlata=@idPlata AND dp.IDOrdonantare is null

IF @cate<>0
BEGIN
PRINT('Ordonontare noua')
INSERT INTO [Ordonantari]
   ([NrDoc],[DataDoc],[IDFurnizor],[ValoareLei],[IDJurnal],[Scop],[DocJust],[AngLegal],[Achitat],[CodUnitate]
   ,[IdModPlata],[TotalDatorat],[TotalAvansuri],[ArtAl],[VizatCFP],[MotivRefuz],[IDResponsabil]
   ,[DataVizaCFP],[NrRegCFP],[IBANSursa],[IBANDest],[IDDocumentPlata])
	SELECT  (SELECT MAX(NrDoc)+1 FROM Ordonantari) AS NrDoc,
	dp.Data AS DataDoc, 
	dp.IDPartener AS IDFurnizor,
	SUM(dd.ValoareTotala +dd.ValoareTVA) As ValoareLei,
	d.IDJurnal AS IDJurnal,
	'PLATA ' + MAX(dp.Numar) + '/' +CAST(DAY(MAX(dp.Data)) AS Varchar(2)) +'.' + CAST(MONTH(MAX(dp.Data)) AS Varchar(2)) + '.' + CAST(YEAR(MAX(dp.Data)) AS Varchar(4)) AS Scop,
	'FACT ' + MAX(d.NrDoc) + '/' +CAST(DAY(MAX(d.DataDoc)) AS Varchar(2)) +'.' + CAST(MONTH(MAX(d.DataDoc)) AS Varchar(2)) + '.' + CAST(YEAR(MAX(d.DataDoc)) AS Varchar(4))  AS [DocJust],
	'ANG LEGAL'	AS [AngLegal],
	0 AS Achitat,
	MAX(d.CodUnitate) AS [CodUnitate],
	(SELECT MIN(IDModPlata) FROM ModPlata) AS [IdModPlata],
	SUM(dd.ValoareTotala + dd.ValoareTVA) As [TotalDatorat],
	0 AS [TotalAvansuri],
	dd.ArtAl aS [ArtAl],
	1 AS [VizatCFP],
	'' AS [MotivRefuz],
	(SELECT MAX(IDResponsabil) FROM Ordonantari) AS [IDResponsabil],
	dp.Data AS [DataVizaCFP],
	(SELECT MAX(NrRegCFP) FROM Ordonantari) AS NrRegCFP,
	MAX(j.IBAN) AS [IBANSursa],
	MAX(f.ContBancar) AS [IBANDest],
	@idPlata AS	[IDDocumentPlata]
	FROM DocumentePlata dp JOIN DocumentePlataDetaliu dpd ON dp.IDDocumentPlata =  dpd.IDDocumentPlata
	JOIN Documente d ON d.IDDocument = dpd.IDDocument		
	JOIN DocumenteDetaliu dd ON d.IDDocument = dd.IDDocument
	JOIN Jurnale j ON j.CodUnitate = d.CodUnitate AND d.IDJurnal = j.IDJurnal
	JOIN Parteneri f ON f.CodUnitate = d.CodUnitate AND d.IDPartener = f.IDPartener
	WHERE dp.IDDocumentPlata = @idPlata  AND dp.IDOrdonantare is Null
	GROUP BY dp.IDPartener,d.IDJurnal,dd.ArtAl,dp.Data
	IF @@ERROR != 0 GOTO EROARE				

	UPDATE [DocumentePlata] SET IdOrdonantare= @@IDENTITY WHERE IDDocumentPlata = @idPlata  AND IDOrdonantare is null
	IF @@ERROR != 0 GOTO EROARE1				

	SET @idOrdonantare = @@IDENTITY
END




GOTO Gata
EROARE:
	RAISERROR ('Eroare la generarea ordonantarii',16,-1)
	GOTO Gata
EROARE1:
	RAISERROR ('Nu se poate seta ordonantarea pentru plata',16,-1)
	GOTO Gata
EROARE2:
	RAISERROR ('Nu pot sterge ordonantarile generate',16,-1)
	GOTO Gata

Gata:
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CreazaArhivaExBug]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CreazaArhivaExBug]
GO

CREATE PROCEDURE [dbo].[CreazaArhivaExBug]
	@An smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @strContAn varchar(40)
	DECLARE @Comanda varchar(3000)
	DECLARE @existTableCont bit
	
	SET @strContAn = 'Ordonantari' + cast(@An AS varchar(4)) 
	SET @existTableCont = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strContAn)
		SET @existTableCont = 1
	
	--verifica existenta tabeleli arhiva
	SET @Comanda = 'SELECT * INTO [' + @strContAn + '] FROM [Ordonantari]'
	
	IF @existTableCont = 0
		EXEC(@Comanda)
		

		

END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[InchideAnExBug]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[InchideAnExBug]
GO


CREATE PROCEDURE [dbo].[InchideAnExBug]  
@pAn as int,
@codUnit as smallint AS

BEGIN

---creaza tabelele corespunzatoare
EXEC CreazaArhivaExBug @An = @pAn
DECLARE @strAn varchar(4)
DECLARE @Comanda varchar(5000)
DECLARE @strCodUnitate varchar(40)

SET @strAn=CAST(@pAn AS varchar(4))
SET @strCodUnitate =  CAST(@codUnit AS varchar(20))




BEGIN TRAN 

PRINT('Ordonantari')
--Ordonantari---------------------------------------
SET @Comanda = 'DELETE FROM [Ordonantari'+@strAn+']  WHERE [CodUnitate]='+@strCodUnitate
EXEC(@Comanda) 
IF @@ERROR != 0 GOTO EROARE

SET @Comanda = 'SET IDENTITY_INSERT [Ordonantari'+@strAn+'] ON;
	INSERT INTO [Ordonantari'+@strAn+'] ([NrDoc]
      ,[DataDoc],[IDFurnizor],[ValoareLei],[IDJurnal],[Scop],[DocJust],[AngLegal],[Achitat],[IdOrdonantare],[CodUnitate]
      ,[IdModPlata],[TotalDatorat],[TotalAvansuri],[ArtAl],[VizatCFP],[MotivRefuz],[IDResponsabil],[DataVizaCFP],[NrRegCFP],[IBANSursa]
      ,[IBANDest],[IDDocumentPlata]) SELECT [NrDoc]
      ,[DataDoc],[IDFurnizor],[ValoareLei],[IDJurnal],[Scop],[DocJust],[AngLegal],[Achitat],[IdOrdonantare],[CodUnitate]
      ,[IdModPlata],[TotalDatorat],[TotalAvansuri],[ArtAl],[VizatCFP],[MotivRefuz],[IDResponsabil],[DataVizaCFP],[NrRegCFP],[IBANSursa]
      ,[IBANDest],[IDDocumentPlata] FROM [Ordonantari] WHERE YEAR(DataDoc)='+@strAn +' AND [CodUnitate]='+@strCodUnitate +
      ';SET IDENTITY_INSERT [Ordonantari'+@strAn+'] OFF'
EXEC(@Comanda) 
IF @@ERROR != 0 GOTO EROARE

SET @Comanda = 'UPDATE [Ordonantari] SET [IDDocumentPlata]=null  WHERE YEAR(DataDoc)='+@strAn +' AND [CodUnitate]=' + @strCodUnitate
EXEC(@Comanda) 
IF @@ERROR != 0 GOTO EROARE

SET @Comanda = 'UPDATE [DocumentePlata] SET [IDOrdonantare]=null  WHERE  EXISTS(SELECT * FROM Ordonantari o  WHERE o.IDOrdonantare=DocumentePlata.IDOrdonantare AND  YEAR(DataDoc)='+@strAn +' AND [CodUnitate]=' + @strCodUnitate + ')'
EXEC(@Comanda) 
IF @@ERROR != 0 GOTO EROARE


PRINT('Sterge arhivat Ordonantari')
SET @Comanda = 'DELETE FROM [Ordonantari] WHERE YEAR(DataDoc)='+@strAn +' AND [CodUnitate]=' + @strCodUnitate
EXEC(@Comanda) 
IF @@ERROR != 0 GOTO EROARE

SET @Comanda = 'UPDATE [ExBugSetup] SET [AnulCurent] = [AnulCurent] + 1 WHERE [CodUnitate] =' + @strCodUnitate 
EXEC(@Comanda) 
IF @@ERROR != 0 GOTO EROARE	


COMMIT


GOTO Gata
EROARE:
	ROLLBACK
	RAISERROR ('Eroare la inchiderea anului!',16,-1)
	GOTO Gata
EROARE1:
	RAISERROR ('!!',16,-1)	
	GOTO Gata
Gata:

END

GO


IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu2011')
BEGIN
	IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu2011' AND COLUMN_NAME = 'ArtAl')
	BEGIN
		ALTER TABLE dbo.DocumenteDetaliu2011 ADD ArtAl varchar(40) NULL 
	END
END
GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu2010')
BEGIN
	IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu2010' AND COLUMN_NAME = 'ArtAl')
	BEGIN
		ALTER TABLE dbo.DocumenteDetaliu2010 ADD ArtAl varchar(40) NULL 
	END
END
GO


IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu2009')
BEGIN
	IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu2009' AND COLUMN_NAME = 'ArtAl')
	BEGIN
		ALTER TABLE dbo.DocumenteDetaliu2009 ADD ArtAl varchar(40) NULL 
	END
END
GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2009')
BEGIN
	IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2009' AND COLUMN_NAME = 'IDJurnal')
	BEGIN
	ALTER TABLE dbo.Documente2009 ADD
		IDJurnal int NULL	
	END
END
go

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010')
BEGIN
	IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010' AND COLUMN_NAME = 'IDJurnal')
	BEGIN
	ALTER TABLE dbo.Documente2010 ADD
		IDJurnal int NULL	
	END
END
go

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2011')
BEGIN
	IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2011' AND COLUMN_NAME = 'IDJurnal')
	BEGIN
	ALTER TABLE dbo.Documente2011 ADD
		IDJurnal int NULL	
	END
END
go

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSporuri' AND COLUMN_NAME = 'IDAngajatSalarizare')
BEGIN
	ALTER TABLE dbo.AngajatiSporuri ADD IDAngajatSalarizare int NULL 

	ALTER TABLE [dbo].AngajatiSporuri  WITH CHECK ADD  CONSTRAINT [FK_AngajatiSporuri_AngajatiSalarizare] FOREIGN KEY([IDAngajatSalarizare]) REFERENCES [dbo].[AngajatiSalarizare] ([IDAngajatSalarizare])

END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'CodUnitate')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD CodUnitate smallint NOT NULL DEFAULT (0)

	ALTER TABLE [dbo].AngajatiSalarizare  WITH CHECK ADD  CONSTRAINT [FK_AngajatiSalarizare_Unitati] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])

END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'Clasa')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD Clasa smallint NOT NULL DEFAULT (0)
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'Grupa')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD Grupa varchar(20) NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'IDJurnal')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD IDJurnal int NULL 

	ALTER TABLE [dbo].AngajatiSalarizare  WITH CHECK ADD  CONSTRAINT [FK_AngajatiSalarizare_Jurnale] FOREIGN KEY([IDJurnal]) REFERENCES [dbo].[Jurnale] ([IDJurnal])

END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'SalarFunctie')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD SalarFunctie decimal(18,2) NOT NULL  DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ConfigMediCab' AND COLUMN_NAME = 'CodUnitate')
BEGIN
	ALTER TABLE dbo.ConfigMediCab ADD CodUnitate smallint NOT NULL  DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SanKitSetup' AND COLUMN_NAME = 'CodUnitate')
BEGIN
	ALTER TABLE dbo.SanKitSetup ADD CodUnitate smallint NOT NULL  DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Chitanta' AND COLUMN_NAME = 'CodUnitate')
BEGIN
	ALTER TABLE dbo.Chitanta ADD CodUnitate smallint NOT NULL  DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Ocupatii' AND COLUMN_NAME = 'Versiune')
BEGIN
	ALTER TABLE dbo.Ocupatii ADD versiune smallint NOT NULL  DEFAULT 0
END
GO

IF  EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[Ocupatii]') AND name = N'IX_Ocupatii_Versiune')
DROP INDEX [IX_Ocupatii_Versiune] ON [dbo].[Ocupatii] WITH ( ONLINE = OFF )
GO

/****** Object:  Index [IX_Ocupatii]    Script Date: 08/10/2012 13:38:51 ******/
CREATE NONCLUSTERED INDEX [IX_Ocupatii_Versiune] ON [dbo].[Ocupatii] 
(
	[CorOcupatie] ASC,
	[versiune] ASC
)
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Ocupatii' AND COLUMN_NAME = 'Terminal')
BEGIN
	ALTER TABLE dbo.Ocupatii ADD Terminal bit NOT NULL DEFAULT 0
END
GO

UPDATE Ocupatii SET Terminal = 0
GO
 
UPDATE Ocupatii SET Terminal = 1 WHERE NOT Exists(SELECT * FROM Ocupatii a WHERE a.IdOcupatieParinte=Ocupatii.IdOcupatie)
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[resuma_CalculSporTrigger]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[resuma_CalculSporTrigger]
GO

CREATE PROCEDURE [dbo].[resuma_CalculSporTrigger] 
	-- Add the parameters for the stored procedure here
	@IdPersoana int,
	@IdAngajatSalarizare int, 
	@IdTipSpor int,
	@Procent decimal(6,2) out,
	@Valoare decimal(18,2) out
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    SET @Procent = 0
    SET @Valoare = 0
    DECLARE @BazaCalculSpor varchar(2)
    DECLARE @Format varchar(1)
    DECLARE @IDOcupatie int
    DECLARE @ProcentG decimal(6,2)
    
    -- Insert statements for procedure here
	SELECT @Procent = Valoare,@BazaCalculSpor = BazaCalculSpor,@Format=Format FROM [TipSpor] WHERE Activ=1 AND IDTipSpor = @IdTipSpor
	IF @Format is null
		return
	
	--Daca e de tip grila ocupatie
	SELECT TOP 1 @ProcentG=Valoare FROM AngajatiOcupatii angO JOIN
	GrileOcupatii grO ON angO.IDOcupatie=grO.IDOcupatie
	WHERE IDPersoana = @IdPersoana AND @Format='F' 
	ORDER BY DeLaData DESC 
	
	IF @Format='F' AND @ProcentG is null
	BEGIN
		SET @Procent = 0
		return
	END
	ELSE
		set @Procent = @ProcentG
	
	SELECT @Valoare = Salar*@Procent/100 FROM [AngajatiSalarizare] as angS 
	  WHERE IDAngajatSalarizare = @IdAngajatSalarizare and @BazaCalculSpor = 'SI'
END

GO


IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[UpdateInsert]'))
DROP TRIGGER [dbo].[UpdateInsert]
GO

CREATE TRIGGER [dbo].[UpdateInsert]
   ON  [dbo].[AngajatiSporuri]
   AFTER INSERT,UPDATE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @IdPersoana int
	DECLARE @IdAngajatSalarizare int
	DECLARE @IdTipSpor int
	DECLARE @Procent decimal(6,2) 
	DECLARE @Valoare decimal(18,2)
	DECLARE @IDPersoanaSpor int
	
	SELECT TOP 1 @IdPersoana=IdPersoana,@IdAngajatSalarizare=IDAngajatSalarizare,@IdTipSpor=IdTipSpor,@IDPersoanaSpor=IdPersoanaSpor FROM inserted
	
	EXEC dbo.resuma_CalculSporTrigger @IdPersoana,@IdAngajatSalarizare,@IdTipSpor, @Procent OUT,@Valoare OUT 	
	
	UPDATE [AngajatiSporuri] SET Procent=@Procent,Valoare=@Valoare WHERE IdPersoanaSpor = @IDPersoanaSpor
    -- Insert statements for trigger here

END

GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ResumaSetup' AND COLUMN_NAME = 'VersiuneCOR')
BEGIN
	ALTER TABLE dbo.ResumaSetup ADD VersiuneCOR smallint NOT NULL  DEFAULT 0
END
GO

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[UpdateVersiuneCOR]'))
DROP TRIGGER [dbo].[UpdateVersiuneCOR]
GO

CREATE TRIGGER [dbo].[UpdateVersiuneCOR]
   ON  [dbo].[ResUmaSetup]
   AFTER UPDATE
AS 
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @Corect smallint
	SET @Corect = 0
	SELECT @corect = (i.VersiuneCOR - r.VersiuneCOR) FROM deleted r JOIN inserted i ON r.[CodUnitate] = i.[CodUnitate]
	IF @Corect < 0 
	BEGIN
		ROLLBACK
		RAISERROR ('O versiune noua nu se poate inlocui cu una mai veche!',-1,0)
		RETURN
	END
    UPDATE [AngajatiOcupatii] SET IDOcupatie = ocup.IDOcupatie FROM Ocupatii ocup,inserted i, Ocupatii oldocup,deleted d 
    WHERE  ocup.versiune = i.versiuneCOR AND oldocup.versiune = d.versiuneCOR AND oldocup.IdOcupatie = [AngajatiOcupatii].IDOcupatie
    AND oldocup.CorOcupatie=ocup.CorOcupatie

    UPDATE [GrileOcupatii] SET IDOcupatie = ocup.IDOcupatie FROM Ocupatii ocup,inserted i, Ocupatii oldocup,deleted d 
    WHERE  ocup.versiune = i.versiuneCOR AND oldocup.versiune = d.versiuneCOR AND oldocup.IdOcupatie = [GrileOcupatii].IDOcupatie
    AND oldocup.CorOcupatie=ocup.CorOcupatie

    UPDATE [GrileOcupatiiDep] SET IDOcupatie = ocup.IDOcupatie FROM Ocupatii ocup,inserted i, Ocupatii oldocup,deleted d 
    WHERE  ocup.versiune = i.versiuneCOR AND oldocup.versiune = d.versiuneCOR AND oldocup.IdOcupatie = [GrileOcupatiiDep].IDOcupatie
    AND oldocup.CorOcupatie=ocup.CorOcupatie


END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_StergeUnitate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_StergeUnitate]
GO


CREATE PROCEDURE [dbo].[fares_StergeUnitate] 
 @CodUnitate smallint AS
BEGIN
DECLARE @NrDoc AS int
SET @NrDoc = 0

BEGIN TRAN

PRINT '[DocumentePlataDetaliu2010]'
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumentePlataDetaliu2010')
BEGIN
DELETE FROM [DocumentePlataDetaliu2010] WHERE IDDocumentPlata IN (SELECT IDDocumentPlata FROM [DocumentePlata2010] WHERE  [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 
END

PRINT('DocumentePlataDetaliu')
DELETE FROM [DocumentePlataDetaliu] WHERE IDDocumentPlata IN (SELECT IDDocumentPlata FROM [DocumentePlata] WHERE  [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[DocumentePlata2010]'
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumentePlata2010')
BEGIN
DELETE FROM [DocumentePlata2010] WHERE  [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
END

PRINT('DocumentePlata')
DELETE FROM [DocumentePlata] WHERE  [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 


PRINT '[DocumenteDetaliu2010]'
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu2010')
BEGIN
DELETE FROM [DocumenteDetaliu2010] WHERE IDDocument IN (SELECT IDDocument FROM [Documente2010] WHERE  [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 
END

PRINT('DocumenteDetaliu')
DELETE FROM [DocumenteDetaliu] WHERE IDDocument IN (SELECT IDDocument FROM [Documente] WHERE  [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 


PRINT('[ArticoleParteneri]')
DELETE FROM [ArticoleParteneri] WHERE IDArticol IN (SELECT IDArticol FROM [articole] WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 


PRINT('[ArticoleVariante]')
DELETE FROM [ArticoleVariante] WHERE IDArticol IN (SELECT IDArticol FROM [articole] WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT('[UMConversie]')
DELETE FROM [UMConversie] WHERE IDArticol IN (SELECT IDArticol FROM [articole] WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 


PRINT('Articole')
DELETE FROM [articole] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[Documente2010]'
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010')
BEGIN
DELETE FROM [Documente2010] WHERE  [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
END

PRINT('Documente')
DELETE FROM [Documente] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare
     
PRINT('ArticoleParteneri')
DELETE FROM [ArticoleParteneri] WHERE IDPartener IN (SELECT IDPartener FROM [Parteneri] WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 
    
PRINT('[ParteneriConturiBancare]')
DELETE FROM [ParteneriConturiBancare] WHERE IDPartener IN (SELECT IDPartener FROM [Parteneri] WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

    
PRINT('Parteneri')
DELETE FROM [Parteneri] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

DELETE FROM [Stocuri] WHERE IDArticol in (SELECT IDArticol FROM [articole] WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 



PRINT 'FaresSetup'
DELETE FROM [FaresSetup] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT 'Trasee'
DELETE FROM [Trasee] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT 'ValoriDimensiuni'
DELETE FROM [ValoriDimensiuni] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 


COMMIT TRAN    
GOTO Gata
Eroare:
  ROLLBACK
  RAISERROR ('Eroare la executia procedurii StergeUnitate',-1,0)
Exista_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine documente!',-1,0)
Exista_Rulaje_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine rulaje - documente!',-1,0)

Gata:

END

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[cabimed_StergeUnitate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[cabimed_StergeUnitate]
GO

CREATE PROCEDURE [dbo].[cabimed_StergeUnitate] 
 @CodUnitate smallint AS
BEGIN
DECLARE @NrDoc AS int
SET @NrDoc = 0

BEGIN TRAN

PRINT '[ParamExUr]'    
DELETE FROM [ParamExUr] WHERE IdCons IN (SELECT c.IdCons FROM [Persoane] p JOIN [Consultatii] c ON c.IdPersoana=p.IdPersoana  WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 


PRINT '[Consultatii]'    
DELETE FROM [Consultatii] WHERE IdPersoana IN (SELECT IdPersoana FROM [Persoane] WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 


PRINT '[ConfigMediCab]'    
DELETE FROM [ConfigMediCab] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 



COMMIT TRAN    
GOTO Gata
Eroare:
  ROLLBACK
  RAISERROR ('Eroare la executia procedurii StergeUnitate',-1,0)
Exista_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine documente!',-1,0)
Exista_Rulaje_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine rulaje - documente!',-1,0)

Gata:

END


GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[balcon_StergeUnitate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[balcon_StergeUnitate]
GO


CREATE PROCEDURE [dbo].[balcon_StergeUnitate] 
 @CodUnitate smallint AS
BEGIN
DECLARE @NrDoc AS int
SET @NrDoc = 0

BEGIN TRAN

DELETE FROM [ParamListe] WHERE [CodUnitate] = @CodUnitate AND [Host]<>'0'
IF @@ERROR <>0
    GOTO Eroare 


DELETE FROM [Arhive] WHERE [CodUnitate] = @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[Rulaje2010]'
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Rulaje2010')
BEGIN
DELETE FROM [Rulaje2010] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
END

DELETE FROM [Rulaje] WHERE [CodUnitate] = @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[RulajeDoc2010]'
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'RulajeDoc2010')
BEGIN
DELETE FROM [RulajeDoc2010] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
END


DELETE FROM [RulajeDoc] WHERE [CodUnitate] = @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

DELETE FROM [BalconSetup] WHERE [CodUnitate] = @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
DELETE FROM [SeriiNumerice] WHERE [CodUnitate] = @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

---initializare bilant           
DELETE FROM [Bilant] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

DELETE FROM [ConturiSpeciale]WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
DELETE FROM [ArticoleAliniate] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

---Conturi corespondente
DELETE FROM [ConturiCoresp]WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

--conturi
DELETE FROM [Conturi] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
    
PRINT '[Conturi2012]'
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Conturi2010')
BEGIN
DELETE FROM [Conturi2010] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
END
           
DELETE FROM [Jurnale] WHERE [CodUnitate] = @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 


DELETE FROM [RezultatPatrimonial] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
          
DELETE FROM [VenituriSiCheltuieli] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

DELETE FROM [ConturiSpeciale] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

COMMIT TRAN    
GOTO Gata
Eroare:
  ROLLBACK
  RAISERROR ('Eroare la executia procedurii StergeUnitate',-1,0)
Exista_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine documente!',-1,0)
Exista_Rulaje_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine rulaje - documente!',-1,0)

Gata:

END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sankit_StergeUnitate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sankit_StergeUnitate]
GO


CREATE PROCEDURE [dbo].[sankit_StergeUnitate] 
 @CodUnitate smallint AS
BEGIN
DECLARE @NrDoc AS int
SET @NrDoc = 0

BEGIN TRAN

PRINT '[ChitantaDetaliu]'    
DELETE FROM [ChitantaDetaliu] WHERE IdChitanta In (SELECT IDChitanta FROM Chitanta WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[Chitanta]'    
DELETE FROM [Chitanta] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[SanKitSetup]'    
DELETE FROM [SanKitSetup] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 



COMMIT TRAN    
GOTO Gata
Eroare:
  ROLLBACK
  RAISERROR ('Eroare la executia procedurii StergeUnitate',-1,0)
Exista_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine documente!',-1,0)
Exista_Rulaje_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine rulaje - documente!',-1,0)

Gata:

END



GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[StergeUnitate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[StergeUnitate]
GO

CREATE PROCEDURE [dbo].[StergeUnitate] 
 @CodUnitate smallint,
 @faraStergereTabelaUnitati bit
 
 
 AS
BEGIN
DECLARE @NrDoc AS int
SET @NrDoc = 0

BEGIN TRAN
IF @CodUnitate=0
	GOTO Eroare2 
EXECUTE amix_StergeUnitate @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
EXECUTE exbug_StergeUnitate @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
EXECUTE cabimed_StergeUnitate @CodUnitate
IF @@ERROR <>0
    GOTO Eroare     
EXECUTE sankit_StergeUnitate @CodUnitate
IF @@ERROR <>0
    GOTO Eroare         
EXECUTE resuma_StergeUnitate @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
EXECUTE fares_StergeUnitate @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
EXECUTE balcon_StergeUnitate @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT 'Sisteme'
DELETE FROM [Sisteme] WHERE IdLocatie IN (SELECT l.IdLocatie FROM Departamente d JOIN Locatii l ON d.IDdepartament=l.IDDepartament WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT 'Locatii'
DELETE FROM [Locatii] WHERE IdDepartament IN (SELECT IdDepartament FROM Departamente WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT 'Departamente'
DELETE FROM [Departamente] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT 'SetariLocale'
DELETE FROM [SetariLocale] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 


UPDATE [Unitati] SET [UnitateSursa]=0 WHERE [UnitateSursa]=@CodUnitate

IF @faraStergereTabelaUnitati=1
BEGIN
	PRINT 'Unitati'
	DELETE FROM [Unitati] WHERE [CodUnitate]=@CodUnitate
	IF @@ERROR <>0
		GOTO Eroare 
END
    


COMMIT TRAN    
GOTO Gata
Eroare:
  ROLLBACK
  RAISERROR ('Eroare la executia procedurii StergeUnitate',-1,0)
Eroare2:
  ROLLBACK
  RAISERROR ('Unitatea demonstrativa nu se poate sterge!',-1,0)
  
Exista_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine documente!',-1,0)
Exista_Rulaje_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine rulaje - documente!',-1,0)

Gata:
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[resuma_StergeUnitate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[resuma_StergeUnitate]
GO

CREATE PROCEDURE [dbo].[resuma_StergeUnitate] 
 @CodUnitate smallint AS
BEGIN
DECLARE @NrDoc AS int
SET @NrDoc = 0

BEGIN TRAN

PRINT '[ContracteMunca]'
DELETE FROM [ContracteMunca] WHERE [CodUnitate] = @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
    
PRINT '[AngajatiAdaosuri]'
DELETE FROM [AngajatiAdaosuri] WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 
PRINT '[AngajatiOcupatii]'
DELETE FROM [AngajatiOcupatii] WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 
PRINT '[AngajatiPontaj]'
DELETE FROM [AngajatiPontaj] WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[AngajatiSporuri]'
DELETE FROM [AngajatiSporuri] WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[AngajatiSalarizare]'
DELETE FROM [AngajatiSalarizare] WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[ConcediiMedicale]'
DELETE FROM [ConcediiMedicale] WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
   GOTO Eroare 

PRINT '[ContracteMunca]'
DELETE FROM [ContracteMunca] WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 
    
PRINT '[PersoaneSuspCM]'
DELETE FROM PersoaneSuspCM WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
    GOTO Eroare     

PRINT '[SituatieMilitara]'
DELETE FROM [SituatieMilitara] WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
    GOTO Eroare  
    
PRINT '[SpecialitatiPersoane]'
DELETE FROM [SpecialitatiPersoane] WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[CalculSporuri]'
DELETE FROM [CalculSporuri] WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[RaportareFoiBoala]'
DELETE FROM [RaportareFoiBoala] WHERE [IDPersoana] IN (SELECT IDPersoana FROM [Persoane] WHERE [CodUnitate] = @CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 



PRINT '[Persoane]'
DELETE FROM [Persoane] WHERE [CodUnitate] = @CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[PosturiVacante]'
DELETE FROM [PosturiVacante] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[ResumaSetup]'
DELETE FROM [ResUmaSetup] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 



COMMIT TRAN    
GOTO Gata
Eroare:
  ROLLBACK
  RAISERROR ('Eroare la executia procedurii StergeUnitate',-1,0)
Exista_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine documente!',-1,0)
Exista_Rulaje_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine rulaje - documente!',-1,0)

Gata:

END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[exbug_StergeUnitate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[exbug_StergeUnitate]
GO


CREATE PROCEDURE [dbo].[exbug_StergeUnitate] 
 @CodUnitate smallint AS
BEGIN
DECLARE @NrDoc AS int
SET @NrDoc = 0

BEGIN TRAN

   
PRINT '[AngajamentLegalDetaliu]'    
DELETE FROM AngajamentLegalDetaliu WHERE IDAL IN (SELECT IDAL FROM AngajamentLegal WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[AngajamentLegalNC]'    
DELETE FROM [AngajamentLegalNC] WHERE IDAL IN (SELECT IDAL FROM AngajamentLegal WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[AngajamentLegal]'    
DELETE FROM [AngajamentLegal] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[AngajamentBugetarDetaliu]'    
DELETE FROM [AngajamentBugetarDetaliu] WHERE IDAB IN (SELECT IDAB FROM AngajamentBugetar WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[AngajamentBugetarNC]'    
DELETE FROM [AngajamentBugetarNC] WHERE IDAB IN (SELECT IDAB FROM AngajamentBugetar WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[AngajamentBugetar]'    
DELETE FROM [AngajamentBugetar] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT 'Ordonantari'    
DELETE FROM Ordonantari WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT 'PropunereAngajareCheltuialaDetaliu'    
DELETE FROM PropunereAngajareCheltuialaDetaliu WHERE IDPac IN (SELECT IDPac FROM PropunereAngajareCheltuiala WHERE [CodUnitate]=@CodUnitate)
IF @@ERROR <>0
    GOTO Eroare 

PRINT '[PropunereAngajareCheltuiala]'    
DELETE FROM [PropunereAngajareCheltuiala] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT 'ArticoleAliniate'    
DELETE FROM ArticoleAliniate WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 

PRINT 'ResponsabilVizaCFP'
DELETE FROM [ResponsabilVizaCFP] WHERE [CodUnitate]=@CodUnitate
IF @@ERROR <>0
    GOTO Eroare 
    
COMMIT TRAN    
GOTO Gata
Eroare:
  ROLLBACK
  RAISERROR ('Eroare la executia procedurii StergeUnitate',-1,0)
Exista_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine documente!',-1,0)
Exista_Rulaje_Documente:
  ROLLBACK
  RAISERROR ('Unitatea nu poate fi stearsa deoarece contine rulaje - documente!',-1,0)

Gata:

END

GO

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [aspnet_Applications] WHERE [LoweredApplicationName]='secon'
IF @Cate= 0 
BEGIN
	INSERT INTO [aspnet_Applications] ([ApplicationName],[LoweredApplicationName],[ApplicationId],[Description],[System],[IDIntern],[MenuName],[NumeDLL])VALUES('SecOn','secon','D4045A52-E820-4C37-85BB-886D8591ABCE','Scheme tretament oncologic',1,'08','Oncologie','SecOn.dll')
END
GO

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='D4045A52-E820-4C37-85BB-886D8591ABCE'

IF @Cate <> 0 
begin
	DELETE [admin_ApplicationMenu] WHERE [ApplicationId]= 'D4045A52-E820-4C37-85BB-886D8591ABCE'
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(8001,'D4045A52-E820-4C37-85BB-886D8591ABCE','Pacienti',NULL,1,'Pacienti',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(8002,'D4045A52-E820-4C37-85BB-886D8591ABCE','Setari',NULL,2,NULL,NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(8020,'D4045A52-E820-4C37-85BB-886D8591ABCE','Scheme de tratament',8002,1,'SchemeTratament',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(8021,'D4045A52-E820-4C37-85BB-886D8591ABCE','Citostatice',8002,2,'Citostatice',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(8022,'D4045A52-E820-4C37-85BB-886D8591ABCE','Localizare',8002,3,'Localizare',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(8023,'D4045A52-E820-4C37-85BB-886D8591ABCE','Durata perfuzie',8002,4,'DurataPerfuzie',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(8024,'D4045A52-E820-4C37-85BB-886D8591ABCE','Pacienti',8002,4,'SetupPacienti',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(8025,'D4045A52-E820-4C37-85BB-886D8591ABCE','Import',8002,4,'Import',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 



IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[onco_Citostatice]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[onco_Citostatice](
		[IDCitostatic] [smallint] IDENTITY(1,1) NOT NULL,
		[Denumire] [varchar](50) NOT NULL,
		[UnitateAdministrare] [varchar](50) NOT NULL,
	 CONSTRAINT [PK_onco_Citostatice] PRIMARY KEY CLUSTERED 
	(
		[IDCitostatic] ASC
	),
	 CONSTRAINT [IX_onco_Citostatice] UNIQUE NONCLUSTERED 
	(
		[Denumire] ASC
	)
	) ON [PRIMARY]

END
GO

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[onco_DurataPerfuzie]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[onco_DurataPerfuzie](
		[IDDurata] [smallint] IDENTITY(1,1) NOT NULL,
		[Denumire] [varchar](50) NOT NULL,
	 CONSTRAINT [PK_onco_DurataPerfuzie] PRIMARY KEY CLUSTERED 
	(
		[IDDurata] ASC
	)
	) ON [PRIMARY]
	
END
GO

IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[onco_ListaProceduri]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[onco_ListaProceduri](
		[IdProcedura] [int] NOT NULL,
		[CodProcedura2011] [nvarchar](6) NULL,
		[CodProcedura] [nvarchar](8) NOT NULL,
		[DenProcedura] [nvarchar](max) NOT NULL,
		[IdBloc] [int] NOT NULL,
	 CONSTRAINT [PK_onco_ListaProceduri] PRIMARY KEY CLUSTERED 
	(
		[IdProcedura] ASC
	)
	) ON [PRIMARY]
	
END

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[onco_Localizare]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[onco_Localizare](
		[IDLocalizare] [smallint] IDENTITY(1,1) NOT NULL,
		[Denumire] [varchar](50) NOT NULL,
		[Cod] [varchar](10) NOT NULL,
	CONSTRAINT [PK_onco_Localizare] PRIMARY KEY CLUSTERED 
	(
		[IDLocalizare] ASC
	)
	) ON [PRIMARY]

END
GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[onco_Protocoale]') AND type in (N'U'))
BEGIN

	CREATE TABLE [dbo].[onco_Protocoale](
		[Durata] [float] NULL,
		[NumarDeZile] [float] NULL,
		[Denumire] [nvarchar](255) NULL,
		[ZileCiclu] [float] NULL,
		[Punctaj] [float] NULL,
		[Observatii] [nvarchar](255) NULL,
		[NumarDeZileTratament] [float] NULL,
		[CIM10] [nvarchar](255) NULL,
		[IDProtocol] [smallint] IDENTITY(1,1) NOT NULL,
		[IDDurataPerfuzie] [smallint] NOT NULL DEFAULT ((4)),
		[IDProcedura] [int] NULL,
	 CONSTRAINT [PK_Protocoale2] PRIMARY KEY CLUSTERED 
	(
		[IDProtocol] ASC
	),
	 CONSTRAINT [IX_onco_Protocoale] UNIQUE NONCLUSTERED 
	(
		[Denumire] ASC
	),
	CONSTRAINT [FK_onco_Protocoale_onco_DurataPerfuzie] FOREIGN KEY([IDDurataPerfuzie]) REFERENCES [dbo].[onco_DurataPerfuzie] ([IDDurata]),
	CONSTRAINT [FK_onco_Protocoale_onco_ListaProceduri] FOREIGN KEY([IDProcedura]) REFERENCES [dbo].[onco_ListaProceduri] ([IdProcedura])
	) ON [PRIMARY]


END
GO


IF  NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[onco_ProtocoaleLocalizare]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[onco_ProtocoaleLocalizare](
		[IDProtocol] [smallint] NOT NULL,
		[IDLocalizare] [smallint] NOT NULL,
		[IDLocalizareProtocol] [smallint] IDENTITY(1,1) NOT NULL,
	 CONSTRAINT [PK_onco_ProtocoaleLocalizare] PRIMARY KEY CLUSTERED 
	(
		[IDLocalizareProtocol] ASC
	),
	CONSTRAINT [FK_onco_ProtocoaleLocalizare_onco_Localizare] FOREIGN KEY([IDLocalizare]) REFERENCES [dbo].[onco_Localizare] ([IDLocalizare]),
	CONSTRAINT [FK_onco_ProtocoaleLocalizare_onco_Protocoale] FOREIGN KEY([IDProtocol]) REFERENCES [dbo].[onco_Protocoale] ([IDProtocol])
	) ON [PRIMARY]


END
GO

IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[onco_Schema]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[onco_Schema](
		[IDSchema] [int] IDENTITY(1,1) NOT NULL,
		[IDProtocol] [smallint] NOT NULL,
		[Ziua] [smallint] NOT NULL DEFAULT ((1)),
		[ZiuaCiclu2] [smallint] NULL,
		[IDCitostatic] [smallint] NOT NULL,
		[Doza] [float] NOT NULL,
		[Explicatie] [varchar](250) NOT NULL DEFAULT (''),
	 CONSTRAINT [PK_onco_Schema] PRIMARY KEY CLUSTERED 
	(
		[IDSchema] ASC
	),
	CONSTRAINT [FK_onco_Schema_onco_Citostatice] FOREIGN KEY([IDCitostatic]) REFERENCES [dbo].[onco_Citostatice] ([IDCitostatic]),
	CONSTRAINT [FK_onco_Schema_onco_Protocoale] FOREIGN KEY([IDProtocol]) REFERENCES [dbo].[onco_Protocoale] ([IDProtocol])
	) ON [PRIMARY]

END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Pacienti]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Pacienti](
		[IDPacient] [int] IDENTITY(1,1) NOT NULL,
		[Nume_Prenume] [varchar](150) NOT NULL,
		[Sex] [smallint] NOT NULL DEFAULT ((0)),
		[DataNasterii] [datetime] NOT NULL DEFAULT (getdate()),
		[Inaltime] [float] NOT NULL DEFAULT ((0)),
		[CodUnitate] [smallint] NOT NULL DEFAULT ((0)),
	 CONSTRAINT [PK_Pacienti] PRIMARY KEY CLUSTERED 
	(
		[IDPacient] ASC
	),
	CONSTRAINT [FK_Pacienti_Unitati] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])
	) ON [PRIMARY]

END
GO

IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Internare]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[Internare](
		[IDInternare] [int] IDENTITY(1,1) NOT NULL,
		[NrFisa] [varchar](20) NOT NULL,
		[DataFisa] [datetime] NOT NULL,
		[IDPacient] [int] NOT NULL,
		[Greutate] [float] NOT NULL,
		[Suprafata] [float] NOT NULL,
		[MedicCurant] [varchar](50) NOT NULL,
		[Creatinina] [float] NOT NULL,
		[Ambulator] [bit] NOT NULL  DEFAULT ((0)),
		[CazNou] [bit] NOT NULL DEFAULT ((1)),
		[Observatii] [varchar](150) NOT NULL,
		[DataCreare] [datetime] NOT NULL  DEFAULT (getdate()),
		[OncoDataStartChimioTer] [datetime] NOT NULL,
		[OncoDataEndChimioTer] [datetime] NOT NULL,
		[OncoLocalizare] [smallint] NOT NULL,
		[OncoCiclu] [smallint] NOT NULL,
		[OncoDataStartCicluUrm] [datetime] NOT NULL,
		[OncoIDProtocol] [smallint] NOT NULL,
		[CodUnitate] [smallint] NOT NULL DEFAULT ((0)),
		[Asistent] [varchar](50) NULL,
		[UserId] [uniqueidentifier] NULL,
	 CONSTRAINT [PK_Internare] PRIMARY KEY CLUSTERED 
	(
		[IDInternare] ASC
	), 
	CONSTRAINT [FK_Internare_onco_Protocoale] FOREIGN KEY([OncoIDProtocol]) REFERENCES [dbo].[onco_Protocoale] ([IDProtocol]),
	CONSTRAINT [FK_Internare_Pacienti] FOREIGN KEY([IDPacient]) REFERENCES [dbo].[Pacienti] ([IDPacient]),
	CONSTRAINT [FK_Internare_Unitati] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])
	) ON [PRIMARY]

END
GO


IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[onco_Setup]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[onco_Setup](
		[PrimaryKey] [smallint] NOT NULL DEFAULT ((0)) ,
		[CodUnitate] [smallint] NOT NULL DEFAULT ((0)) ,
		[AfiseazaProprietarDocument] [bit] NOT NULL  DEFAULT ((0)),
		[AfiseazaSemnaturiTiparire] [bit] NOT NULL DEFAULT ((1)),
	 CONSTRAINT [PK_onco_Setup] PRIMARY KEY CLUSTERED 
	(
		[PrimaryKey] ASC,
		[CodUnitate] ASC
	),
	CONSTRAINT [FK_onco_Setup_Unitati] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])
	) ON [PRIMARY]
END
GO


IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[onco_SchemaInternare]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[onco_SchemaInternare](
		[IDSchema] [int] IDENTITY(1,1) NOT NULL,
		[IDProtocol] [smallint] NOT NULL,
		[Ziua] [smallint] NOT NULL  DEFAULT ((1)),
		[ZiuaCiclu2] [smallint] NULL,
		[IDCitostatic] [smallint] NOT NULL,
		[Doza] [float] NOT NULL,
		[Explicatie] [varchar](250) NOT NULL  DEFAULT (''),
		[IDInternare] [int] NOT NULL,
		[DozaRecomandata] [float] NOT NULL DEFAULT ((0)),
		[DozaPrescrisa] [float] NOT NULL DEFAULT ((0)),
		[UM] [varchar](50) NULL,
	 CONSTRAINT [PK_onco_SchemaInternare] PRIMARY KEY CLUSTERED 
	(
		[IDSchema] ASC
	),
	CONSTRAINT [FK_onco_SchemaInternare_Internare] FOREIGN KEY([IDInternare]) REFERENCES [dbo].[Internare] ([IDInternare]),
	CONSTRAINT [FK_onco_SchemaInternare_onco_Citostatice] FOREIGN KEY([IDCitostatic]) REFERENCES [dbo].[onco_Citostatice] ([IDCitostatic]),
	CONSTRAINT [FK_onco_SchemaInternare_onco_Protocoale] FOREIGN KEY([IDProtocol]) REFERENCES [dbo].[onco_Protocoale] ([IDProtocol])
	) ON [PRIMARY]


END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[onco_viewAsistent]'))
DROP VIEW [dbo].[onco_viewAsistent]
GO

CREATE VIEW [dbo].[onco_viewAsistent]
AS
SELECT DISTINCT Asistent
FROM         dbo.Internare

GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[onco_ViewLocalizareProtocol]'))
DROP VIEW [dbo].[onco_ViewLocalizareProtocol]
GO

CREATE VIEW [dbo].[onco_ViewLocalizareProtocol]
AS
SELECT     dbo.onco_ProtocoaleLocalizare.IDLocalizare, dbo.onco_ProtocoaleLocalizare.IDLocalizareProtocol, dbo.onco_Protocoale.*
FROM         dbo.onco_ProtocoaleLocalizare INNER JOIN
                      dbo.onco_Protocoale ON dbo.onco_ProtocoaleLocalizare.IDProtocol = dbo.onco_Protocoale.IDProtocol

GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[onco_viewMedic]'))
DROP VIEW [dbo].[onco_viewMedic]
GO

CREATE VIEW [dbo].[onco_viewMedic]
AS
SELECT DISTINCT MedicCurant
FROM         dbo.Internare

GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[onco_viewSchema]'))
DROP VIEW [dbo].[onco_viewSchema]
GO

CREATE VIEW [dbo].[onco_viewSchema]
AS
SELECT     dbo.onco_Schema.*, dbo.onco_Citostatice.UnitateAdministrare
FROM         dbo.onco_Schema INNER JOIN
                      dbo.onco_Citostatice ON dbo.onco_Schema.IDCitostatic = dbo.onco_Citostatice.IDCitostatic

GO


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[onco_viewSchemaInternare]'))
DROP VIEW [dbo].[onco_viewSchemaInternare]
GO

CREATE VIEW [dbo].[onco_viewSchemaInternare]
AS
SELECT     dbo.onco_SchemaInternare.Ziua, dbo.onco_SchemaInternare.ZiuaCiclu2, dbo.onco_Citostatice.Denumire, dbo.onco_SchemaInternare.Doza, 
                      dbo.onco_SchemaInternare.Explicatie, dbo.onco_SchemaInternare.IDInternare, dbo.onco_SchemaInternare.DozaRecomandata, 
                      dbo.onco_SchemaInternare.DozaPrescrisa, dbo.onco_SchemaInternare.UM, DATEADD(day, dbo.onco_SchemaInternare.Ziua, dbo.Internare.OncoDataStartChimioTer) 
                      AS OncoDataStartChimioTer, dbo.onco_SchemaInternare.IDSchema
FROM         dbo.onco_SchemaInternare INNER JOIN
                      dbo.onco_Citostatice ON dbo.onco_SchemaInternare.IDCitostatic = dbo.onco_Citostatice.IDCitostatic INNER JOIN
                      dbo.Internare ON dbo.onco_SchemaInternare.IDInternare = dbo.Internare.IDInternare

GO





IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'onco_Protocoale' AND COLUMN_NAME = 'Activ')
BEGIN
	ALTER TABLE dbo.onco_Protocoale ADD Activ bit NOT NULL DEFAULT 1
END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[onco_ViewLocalizareProtocol]'))
DROP VIEW [dbo].[onco_ViewLocalizareProtocol]
GO

CREATE VIEW [dbo].[onco_ViewLocalizareProtocol]
AS
SELECT     dbo.onco_ProtocoaleLocalizare.IDLocalizare, dbo.onco_ProtocoaleLocalizare.IDLocalizareProtocol, dbo.onco_Protocoale.Durata, dbo.onco_Protocoale.NumarDeZile, 
                      dbo.onco_Protocoale.Denumire, dbo.onco_Protocoale.ZileCiclu, dbo.onco_Protocoale.Punctaj, dbo.onco_Protocoale.Observatii, 
                      dbo.onco_Protocoale.NumarDeZileTratament, dbo.onco_Protocoale.CIM10, dbo.onco_Protocoale.IDProtocol, dbo.onco_Protocoale.IDDurataPerfuzie, 
                      dbo.onco_Protocoale.IDProcedura, dbo.onco_Protocoale.Activ
FROM         dbo.onco_ProtocoaleLocalizare INNER JOIN
                      dbo.onco_Protocoale ON dbo.onco_ProtocoaleLocalizare.IDProtocol = dbo.onco_Protocoale.IDProtocol

GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[onco_viewProtocoaleCitostatice]'))
DROP VIEW [dbo].[onco_viewProtocoaleCitostatice]
GO

CREATE VIEW [dbo].[onco_viewProtocoaleCitostatice]
AS
SELECT     dbo.onco_Protocoale.Durata, dbo.onco_Protocoale.NumarDeZile, dbo.onco_Protocoale.Denumire, dbo.onco_Protocoale.ZileCiclu, dbo.onco_Protocoale.Punctaj, 
                      dbo.onco_Protocoale.Observatii, dbo.onco_Protocoale.NumarDeZileTratament, dbo.onco_Protocoale.CIM10, dbo.onco_Protocoale.IDProtocol, 
                      dbo.onco_Protocoale.IDDurataPerfuzie, dbo.onco_Protocoale.IDProcedura, dbo.onco_Protocoale.Activ, onco_Schema.IDCitostatic
FROM         dbo.onco_Protocoale INNER JOIN
                          (SELECT DISTINCT IDCitostatic, IDProtocol
                            FROM          dbo.onco_Schema AS onco_Schema_1) AS onco_Schema ON dbo.onco_Protocoale.IDProtocol = onco_Schema.IDProtocol

GO


IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[Stoc_DocumenteDetaliu_Insert]'))
DROP TRIGGER [dbo].[Stoc_DocumenteDetaliu_Insert]
GO

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[Stoc_DocumenteDetaliu_Update]'))
DROP TRIGGER [dbo].[Stoc_DocumenteDetaliu_Update]
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'Productie')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD Productie bit NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Articole' AND COLUMN_NAME = 'Lungime')
BEGIN
	ALTER TABLE dbo.Articole ADD Lungime float NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Articole' AND COLUMN_NAME = 'Latime')
BEGIN
	ALTER TABLE dbo.Articole ADD Latime float NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Articole' AND COLUMN_NAME = 'Grosime')
BEGIN
	ALTER TABLE dbo.Articole ADD Grosime float NULL 
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Articole' AND COLUMN_NAME = 'Raft')
BEGIN
	ALTER TABLE dbo.Articole ADD Raft varchar(50) NULL 
END
GO


IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ProductieOperatiuni]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ProductieOperatiuni](
		[IDOperatiune] [int] IDENTITY(1,1) NOT NULL,
		[Denumire] [varchar](50) NOT NULL,
		[Descriere] [varchar](250) NOT NULL,
		[Utilaj] [varchar](100) NOT NULL,
		[NrPersoane] [smallint] NOT NULL DEFAULT ((0)),
		[Randament] [float] NOT NULL DEFAULT ((0)) ,
		[Pozitie] [smallint] NOT NULL DEFAULT ((0)) ,
		[IDArticolFinit] [int] NOT NULL,
		[Activ] [bit] NOT NULL DEFAULT(0),
	 CONSTRAINT [PK_ProductieOperatiuni] PRIMARY KEY CLUSTERED 
	(
		[IDOperatiune] ASC
	),
	CONSTRAINT [FK_ProductieOperatiuni_Articole] FOREIGN KEY([IDArticolFinit]) REFERENCES [dbo].[Articole] ([IDArticol])
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ProductieArticoleOperatiuni]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ProductieArticoleOperatiuni](
		[IDArticolOperatiune] [int] IDENTITY(1,1) NOT NULL,
		[IDOperatiune] [int] NOT NULL,
		[IDArticol] [int] NOT NULL,
		[Intrare] [bit] NOT NULL DEFAULT ((0)),
		[Multiplicare] [float] NOT NULL DEFAULT(0),
	 CONSTRAINT [PK_ProductieArticoleOperatiuni] PRIMARY KEY CLUSTERED 
	(
		[IDArticolOperatiune] ASC
	),
	CONSTRAINT [FK_ProductieArticoleOperatiuni_Articole] FOREIGN KEY([IDArticol])
	REFERENCES [dbo].[Articole] ([IDArticol]),
	 CONSTRAINT [FK_ProductieArticoleOperatiuni_ProductieOperatiuni] FOREIGN KEY([IDOperatiune])
	REFERENCES [dbo].[ProductieOperatiuni] ([IDOperatiune])
	) ON [PRIMARY]
END
GO



IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ValutaCurs' AND COLUMN_NAME = 'IDBanca')
BEGIN
	ALTER TABLE dbo.ValutaCurs ADD IDBanca smallint NOT NULL 

	ALTER TABLE [dbo].ValutaCurs  WITH CHECK ADD  CONSTRAINT [FK_ValutaCurs_Banca] FOREIGN KEY([IDBanca]) REFERENCES [dbo].[Banci] ([IDBanca])

	ALTER TABLE [dbo].[ValutaCurs] ADD  CONSTRAINT [IX_ValutaCurs] UNIQUE NONCLUSTERED 
	(
		[CodValuta] ASC,
		[IDBanca] ASC,
		[Data] ASC
	)
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Valuta' AND COLUMN_NAME = 'MonedaImplicita')
BEGIN
	ALTER TABLE dbo.Valuta ADD MonedaImplicita bit NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'IDBancaImplicita')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD IDBancaImplicita smallint NOT NULL DEFAULT 0
	ALTER TABLE [dbo].FaresSetup  WITH CHECK ADD  CONSTRAINT [FK_FaresSetup_BancaImplicita] FOREIGN KEY([IDBancaImplicita]) REFERENCES [dbo].[Banci] ([IDBanca])
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'ImplementareAmbalaje')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD ImplementareAmbalaje bit NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Stocuri' AND COLUMN_NAME = 'PretValuta')
BEGIN
	ALTER TABLE dbo.Stocuri ADD PretValuta decimal(25,5) NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Stocuri' AND COLUMN_NAME = 'PretCodValuta')
BEGIN
	ALTER TABLE dbo.Stocuri ADD PretCodValuta smallint NOT NULL DEFAULT 0

	ALTER TABLE [dbo].Stocuri  WITH CHECK ADD  CONSTRAINT [FK_Stocuri_Valuta] FOREIGN KEY([PretCodValuta]) REFERENCES [dbo].[Valuta] ([CodValuta])
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Parteneri' AND COLUMN_NAME = 'ConditiiDePlata')
BEGIN
	ALTER TABLE dbo.Parteneri ADD ConditiiDePlata varchar(250) NULL 
END
GO

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[Stoc_DocumenteDetaliu_Delete]'))
DROP TRIGGER [dbo].[Stoc_DocumenteDetaliu_Delete]
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_ParteneriCUI]'))
DROP VIEW [dbo].[fares_ParteneriCUI]
GO

CREATE VIEW [dbo].[fares_ParteneriCUI]
AS
SELECT     IDPartener, CodUnitate, CUI, Denumire + ' (' + LTRIM(RTRIM(CAST(CUI AS VARCHAR(20)))) + ')' AS Denumire, ConditiiDePlata
FROM         dbo.Parteneri

GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'AreDocGestStoc')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD AreDocGestStoc bit NOT NULL DEFAULT 1
END
GO



DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9' and [HandlerName]='Productie'
IF @Cate= 0 
begin
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(4300,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Productie',null,135,'Productie',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 
go

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_CautaArticole]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_CautaArticole]
GO

CREATE PROCEDURE [dbo].[fares_CautaArticole]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint,
	@CodArticol varchar(50),
	@Denumire varchar(100),
	@ContArticol TipCont,
	@ContCheltuiala TipCont,
	@IDCategorie smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT * FROM Articole
	WHERE CodUnitate=@CodUnitate and 
	(@CodArticol='' OR CodArticol LIKE '%' + @CodArticol + '%') AND
	(@Denumire='' OR Denumire LIKE '%' + @Denumire + '%') AND 
	(@ContArticol='' OR Cont = @ContArticol) AND 
	(@ContCheltuiala='' OR ContCheltuiala =@ContCheltuiala) AND
	(@IDCategorie=-1 OR IDCategorie = @IDCategorie)
	
END

GO


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewArticolProductie]'))
DROP VIEW [dbo].[fares_viewArticolProductie]
GO

CREATE VIEW [dbo].[fares_viewArticolProductie]
AS
SELECT     IDArticol, Denumire, COALESCE (Lungime * Latime / 1000000, 0) AS Suprafata, CodUnitate, COALESCE
                          ((SELECT     SUM(StocInitial + StocPrecedent + Intrari - Iesiri) AS Stoc
                              FROM         dbo.Stocuri AS s
                              WHERE     (a.IDArticol = IDArticol)), 0) AS StocCurent,IDCategorie
FROM         dbo.Articole AS a

GO

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [TipDocument] WHERE [IDTipDocument]=14
IF @Cate= 0 
BEGIN
	SET IDENTITY_INSERT [TipDocument] ON
	INSERT INTO [tipDocument] ([IDTipDocument],[Denumire],[TipOperatie],[SePlateste],[ModificaStoc] )VALUES(14,'Aviz de expeditie','O',0,1)           
	SET IDENTITY_INSERT [TipDocument] OFF
END
GO

DECLARE @Cate3 int
SELECT @Cate3 = COUNT(*) FROM [admin_ApplicationDocuments] WHERE [IDTipDocument]=14
IF @Cate3= 0 
BEGIN
INSERT INTO [admin_ApplicationDocuments] ([IDTipDocument],[ApplicationID])VALUES(14,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9')
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'IDSerieAE')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD
	IDSerieAE nvarchar(20) NULL 
	ALTER TABLE [dbo].FaresSetup  WITH CHECK ADD  CONSTRAINT [FK_FaresSetup_SeriiNumerice_Aviz_Expeditie] FOREIGN KEY([IDSerieAE],[CodUnitate]) REFERENCES [dbo].[SeriiNumerice] ([IDSerie],[CodUnitate])
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'AvizExpeditieCuTVA')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD AvizExpeditieCuTVA bit NOT NULL DEFAULT (0)

END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ProductieRealizata]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ProductieRealizata](
		[IDRealizat] [int] IDENTITY(1,1) NOT NULL,
		[IDDocumentDetaliu] [bigint] NOT NULL,
		[Data] [datetime] NOT NULL DEFAULT (getdate()),
		[Cantitate] [float] NOT NULL DEFAULT ((0)),
	 CONSTRAINT [PK_ProductieRealizata] PRIMARY KEY CLUSTERED 
	(
		[IDRealizat] ASC
	),
	CONSTRAINT [FK_ProductieRealizata_DocumenteDetaliu] FOREIGN KEY([IDDocumentDetaliu]) REFERENCES [dbo].[DocumenteDetaliu] ([IDDocumentDetaliu])
	) ON [PRIMARY]
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_AdaugaProductieRealizata]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_AdaugaProductieRealizata]
GO

CREATE PROCEDURE [dbo].[fares_AdaugaProductieRealizata]
	-- Add the parameters for the stored procedure here
	@IDDocumenteDetaliuSelectate varchar(2000), 
	@DataProductie varchar(10)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF LEN(LTRIM(RTRIM(@IDDocumenteDetaliuSelectate)))=0
		return 
    DECLARE @sel varchar(5000)
    
	SET @sel = 'INSERT INTO [ProductieRealizata]([IDDocumentDetaliu],[Data],[Cantitate]) 
		(SELECT [IDDocumentDetaliu],''' + @DataProductie + ''',dd.Cantitate - 
		COALESCE((SELECT SUM(Cantitate) FROM [ProductieRealizata] pr WHERE pr.[IDDocumentDetaliu]=dd.[IDDocumentDetaliu]),0) AS [newCantit] 
		FROM [DocumenteDetaliu] dd 
		WHERE [IDDocumentDetaliu] IN (' +  LTRIM(RTRIM(@IDDocumenteDetaliuSelectate)) + '))'
	PRINT(@sel)	
	EXEC(@sel)
	DELETE FROM [ProductieRealizata] WHERE [Cantitate]=0
	
END

GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_FisaProductie]'))
DROP VIEW [dbo].[fares_FisaProductie]
GO

CREATE VIEW [dbo].[fares_FisaProductie]
AS
SELECT     TOP (100) PERCENT dbo.ProductieOperatiuni.Pozitie, dbo.ProductieOperatiuni.Denumire, dbo.ProductieOperatiuni.Descriere, dbo.ProductieOperatiuni.Utilaj, 
                      dbo.ProductieRealizata.Cantitate, dbo.ProductieRealizata.Data, dbo.Articole.Denumire AS DenumireProdus, dbo.Documente.DataScadenta, 
                      dbo.Documente.NrDoc
FROM         dbo.DocumenteDetaliu INNER JOIN
                      dbo.ProductieRealizata ON dbo.DocumenteDetaliu.IDDocumentDetaliu = dbo.ProductieRealizata.IDDocumentDetaliu INNER JOIN
                      dbo.ProductieOperatiuni ON dbo.ProductieOperatiuni.IDArticolFinit = dbo.DocumenteDetaliu.IDArticol INNER JOIN
                      dbo.Articole ON dbo.DocumenteDetaliu.IDArticol = dbo.Articole.IDArticol AND dbo.ProductieOperatiuni.IDArticolFinit = dbo.Articole.IDArticol INNER JOIN
                      dbo.Documente ON dbo.DocumenteDetaliu.IDDocument = dbo.Documente.IDDocument
WHERE     (dbo.ProductieOperatiuni.Activ <> 0)
ORDER BY dbo.ProductieOperatiuni.Pozitie
GO

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9' and [Name]='Gestiunea Stocurilor'
IF @Cate= 0 
begin
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(4850,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Gestiunea Stocurilor',4800,20,NULL,NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(4851,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Stocuri',4850,21,'Lista_Stocuri',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(4852,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Rulaje',4850,22,'Lista_Rulaje',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(4853,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Fisa de Magazie',4850,23,'Lista_FisaMagazie',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 
go


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitParameters]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[SplitParameters]
GO

CREATE  FUNCTION [dbo].[SplitParameters](@sText varchar(8000), @sDelim varchar(20) = ' ')
RETURNS @retArray 
TABLE (
	idx smallint Primary Key, 
	value varchar(8000)
)
AS
BEGIN
	DECLARE @idx int,
	@value varchar(8000),
	@bcontinue bit,
	@iStrike int,
	@iDelimlength int

	IF @sDelim = 'Space'
		BEGIN
			SET @sDelim = ' '
		END

	SET @idx = 0
	SET @sText = LTrim(RTrim(@sText))
	SET @iDelimlength = DATALENGTH(@sDelim)
	SET @bcontinue = 1

	if(Len(@sText) = 0)
		return

	IF NOT ((@iDelimlength = 0) or (@sDelim = 'Empty'))
	BEGIN
		WHILE @bcontinue = 1
		BEGIN
			--Daca se poate gasii primul delimitator in text, extrage primul element si
			--il insereaza cu indexul sau in tabela rezultat
			IF CHARINDEX(@sDelim, @sText)>0
			BEGIN
				SET @value = SUBSTRING(@sText,1,CHARINDEX(@sDelim,@sText)-1)
				BEGIN
					INSERT @retArray (idx, value)
					VALUES (@idx, @value)
				END
				--Elimina elementul si delimitatorul sau de la inceputul sirului
				--incrementeaza indexul ciclului
				SET @iStrike = DATALENGTH(@value) + @iDelimlength
				SET @idx = @idx + 1
				SET @sText = LTrim(Right(@sText,DATALENGTH(@sText) - @iStrike))
			END
			ELSE
			BEGIN
				--Daca nu gasim delimitator in text, @sText este ultima valoare dintabela
				SET @value = @sText
				INSERT @retArray (idx, value)
				VALUES (@idx, @value)
				--Termina bucla.
				SET @bcontinue = 0
			END
		END
	END
	
	RETURN
END
GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitIntParameters]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[SplitIntParameters]
GO

CREATE  FUNCTION [dbo].[SplitIntParameters](@sText varchar(8000), @sDelim varchar(20) = ' ')
RETURNS @retArray 
TABLE (
	idx smallint Primary Key, 
	value int
)
AS
BEGIN
	DECLARE @idx int,
	@value varchar(8000),
	@bcontinue bit,
	@iStrike int,
	@iDelimlength int

	IF @sDelim = 'Space'
		BEGIN
			SET @sDelim = ' '
		END

	SET @idx = 0
	SET @sText = LTrim(RTrim(@sText))
	SET @iDelimlength = DATALENGTH(@sDelim)
	SET @bcontinue = 1

	if(Len(@sText) = 0)
		return

	IF NOT ((@iDelimlength = 0) or (@sDelim = 'Empty'))
	BEGIN
		WHILE @bcontinue = 1
		BEGIN
			--Daca se poate gasii primul delimitator in text, extrage primul element si
			--il insereaza cu indexul sau in tabela rezultat
			IF CHARINDEX(@sDelim, @sText)>0
			BEGIN
				SET @value = SUBSTRING(@sText,1,CHARINDEX(@sDelim,@sText)-1)
				BEGIN
					INSERT @retArray (idx, value)
					VALUES (@idx, CAST(@value as int))
				END
				--Elimina elementul si delimitatorul sau de la inceputul sirului
				--incrementeaza indexul ciclului
				SET @iStrike = DATALENGTH(@value) + @iDelimlength
				SET @idx = @idx + 1
				SET @sText = LTrim(Right(@sText,DATALENGTH(@sText) - @iStrike))
			END
			ELSE
			BEGIN
				--Daca nu gasim delimitator in text, @sText este ultima valoare dintabela
				SET @value = @sText
				INSERT @retArray (idx, value)
				VALUES (@idx, CAST(@value as int))
				--Termina bucla.
				SET @bcontinue = 0
			END
		END
	END
	
	RETURN
END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SplitBigIntParameters]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[SplitBigIntParameters]
GO

CREATE  FUNCTION [dbo].[SplitBigIntParameters](@sText varchar(8000), @sDelim varchar(20) = ' ')
RETURNS @retArray 
TABLE (
	idx smallint Primary Key, 
	value bigint
)
AS
BEGIN
	DECLARE @idx int,
	@value varchar(8000),
	@bcontinue bit,
	@iStrike int,
	@iDelimlength int

	IF @sDelim = 'Space'
		BEGIN
			SET @sDelim = ' '
		END

	SET @idx = 0
	SET @sText = LTrim(RTrim(@sText))
	SET @iDelimlength = DATALENGTH(@sDelim)
	SET @bcontinue = 1

	if(Len(@sText) = 0)
		return

	IF NOT ((@iDelimlength = 0) or (@sDelim = 'Empty'))
	BEGIN
		WHILE @bcontinue = 1
		BEGIN
			--Daca se poate gasii primul delimitator in text, extrage primul element si
			--il insereaza cu indexul sau in tabela rezultat
			IF CHARINDEX(@sDelim, @sText)>0
			BEGIN
				SET @value = SUBSTRING(@sText,1,CHARINDEX(@sDelim,@sText)-1)
				BEGIN
					INSERT @retArray (idx, value)
					VALUES (@idx, CAST(@value as bigint))
				END
				--Elimina elementul si delimitatorul sau de la inceputul sirului
				--incrementeaza indexul ciclului
				SET @iStrike = DATALENGTH(@value) + @iDelimlength
				SET @idx = @idx + 1
				SET @sText = LTrim(Right(@sText,DATALENGTH(@sText) - @iStrike))
			END
			ELSE
			BEGIN
				--Daca nu gasim delimitator in text, @sText este ultima valoare dintabela
				SET @value = @sText
				INSERT @retArray (idx, value)
				VALUES (@idx, CAST(@value as bigint))
				--Termina bucla.
				SET @bcontinue = 0
			END
		END
	END
	
	RETURN
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaListaStocuri]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaListaStocuri]
GO


CREATE PROCEDURE [dbo].[fares_FiltreazaListaStocuri] 
	-- Add the parameters for the stored procedure here
	@filtruPart varchar(8000),
	@filtruArt varchar(8000),
	@filtruCat varchar(8000),
	@laData datetime,
	@StocuriZero bit,
	@Comparatie smallint,
	@ValoareStoc decimal(25,5),
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    SELECT *,v.Stoc*v.ValoareUnitara ValoareTotala FROM
    (SELECT art.IDArticol,docDet.ValoareUnitara,
    MAX(art.Denumire) DenumireArticol,MAX(tca.Denumire) DenumireCategorie, MAX(part.Denumire) DenumirePartener,MAX(um.Denumire) DenumireUM,
    MAX(st.StocInitial) StocInitial,
    MAX(st.StocPrecedent) StocPrecedent,
    SUM(CASE WHEN td.TipOperatie = 'I' AND td.ModificaStoc=1 AND doc.AreDocGestStoc=1 AND doc.DataDoc<=@laData THEN docDet.Cantitate  ELSE 0 END) Intrari ,
    SUM(CASE WHEN td.TipOperatie = 'O' AND td.ModificaStoc=1 AND doc.AreDocGestStoc=1 AND doc.DataDoc<=@laData THEN docDet.Cantitate  ELSE 0 END) Iesiri,
    MAX(st.StocInitial) + MAX(st.StocPrecedent)+
    SUM(CASE WHEN td.TipOperatie = 'I' AND td.ModificaStoc=1 AND doc.AreDocGestStoc=1 AND doc.DataDoc<=@laData THEN docDet.Cantitate  ELSE 0 END)-
    SUM(CASE WHEN td.TipOperatie = 'O' AND td.ModificaStoc=1 AND doc.AreDocGestStoc=1 AND doc.DataDoc<=@laData THEN docDet.Cantitate  ELSE 0 END) Stoc
    FROM [Articole] art
    LEFT OUTER JOIN [DocumenteDetaliu] docDet ON docDet.IDArticol = art.IDArticol
    JOIN [Documente] doc ON doc.IDDocument = docDet.IDDocument
    JOIN [TipDocument] td ON doc.IDTipDocument = td.IDTipDocument
    JOIN [Parteneri] part ON doc.IDPartener = part.IDPartener
    JOIN [TipCategoriiArticole] tca ON art.IDCategorie = tca.IDCategorie
    LEFT OUTER JOIN [Stocuri] st ON st.IDArticol = art.IDArticol
    JOIN UnitatiMasura um ON art.IDUnitateMasura = um.IDUnitateMasura
    WHERE 
    art.CodUnitate = @CodUnitate AND
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (art.IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (part.IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruCat)))=0 OR (tca.IDCategorie IN (SELECT CAST(fart.value as smallint) FROM dbo.SplitParameters(@filtruCat,',') fart))) 
    GROUP BY art.IDArticol,docDet.ValoareUnitara)
    v
    WHERE 
    (@StocuriZero=1 OR Coalesce(Stoc,0)<>0) AND
    ((@Comparatie=0 AND Coalesce(Stoc,0) >@ValoareStoc) OR (@Comparatie=1 AND Coalesce(Stoc,0) >=@ValoareStoc) OR (@Comparatie=2 AND Coalesce(Stoc,0) =@ValoareStoc)
     OR (@Comparatie=3 AND Coalesce(Stoc,0) <=@ValoareStoc) OR (@Comparatie=4 AND Coalesce(Stoc,0) <@ValoareStoc) OR (@Comparatie=5 AND Coalesce(Stoc,0) <>@ValoareStoc))
     
END



GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010')
BEGIN
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010' AND COLUMN_NAME = 'IDJurnal')
BEGIN
	ALTER TABLE dbo.Documente2010 ADD IDJurnal int NULL
	ALTER TABLE dbo.Documente2010 ADD CONSTRAINT FK_Documente2010_Jurnale FOREIGN KEY(IDJurnal) 
		REFERENCES dbo.Jurnale (IDJurnal) 
END

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010' AND COLUMN_NAME = 'CursValutar')
BEGIN
	ALTER TABLE dbo.Documente2010 ADD CursValutar decimal(18,4) NOT NULL DEFAULT 0
END


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010' AND COLUMN_NAME = 'CodValuta')
BEGIN
	ALTER TABLE dbo.Documente2010 ADD CodValuta smallint NOT NULL DEFAULT 0

	ALTER TABLE [dbo].Documente2010  WITH CHECK ADD  CONSTRAINT [FK_Documente2010_Valuta] FOREIGN KEY([CodValuta]) REFERENCES [dbo].[Valuta] ([CodValuta])
END


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010' AND COLUMN_NAME = 'AreDocGestStoc')
BEGIN
	ALTER TABLE dbo.Documente2010 ADD AreDocGestStoc bit NOT NULL DEFAULT 1
END


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010' AND COLUMN_NAME = 'DataStartProductie')
BEGIN
	ALTER TABLE dbo.Documente2010 ADD DataStartProductie DateTime NOT NULL DEFAULT (getdate())
END

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010' AND COLUMN_NAME = 'Serie')
BEGIN
	ALTER TABLE dbo.Documente2010 ADD Serie varchar(10) NULL 
END


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente2010' AND COLUMN_NAME = 'Numar')
BEGIN
	ALTER TABLE dbo.Documente2010 ADD Numar varchar(20) NULL 
END



END
GO



IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu2010')
BEGIN

	IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu2010' AND COLUMN_NAME = 'ValoareUnitaraValuta')
	BEGIN
		ALTER TABLE dbo.DocumenteDetaliu2010 ADD ValoareUnitaraValuta decimal(25,5) NOT NULL DEFAULT 0
	END

	IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu2010' AND COLUMN_NAME = 'ArtAl')
	BEGIN
		ALTER TABLE dbo.DocumenteDetaliu2010 ADD ArtAl varchar(40) NULL 
	END

END
GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumentePlata2010')
BEGIN
	IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumentePlata2010' AND COLUMN_NAME = 'IDOrdonantare')
	BEGIN
		ALTER TABLE dbo.DocumentePlata2010 ADD IDOrdonantare int NULL 

		ALTER TABLE [dbo].DocumentePlata2010  WITH CHECK ADD  CONSTRAINT [FK_DocumentePlata2010_Ordonantare] FOREIGN KEY([IDOrdonantare]) REFERENCES [dbo].[Ordonantari] ([IDOrdonantare])
	END
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CreazaArhivaFares]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CreazaArhivaFares]
GO

CREATE PROCEDURE [dbo].[CreazaArhivaFares]
	@An smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @strTabelaAn varchar(40)
	DECLARE @Comanda varchar(8000)
	DECLARE @existTable bit
	
	SET @strTabelaAn = cast(@An AS varchar(4)) 
	SET @existTable = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE 'Documente' + @strTabelaAn)
		SET @existTable = 1
	
	--verifica existenta tabeleli arhiva
	SET @Comanda = 'CREATE TABLE [dbo].[Documente'+@strTabelaAn+'](
		[IDDocument] [bigint] NOT NULL,
		[NrDoc] [varchar](20) NOT NULL,
		[DataDoc] [datetime] NOT NULL,
		[IDPartener] [bigint] NOT NULL,
		[CodUnitate] [smallint] NOT NULL DEFAULT 0,
		[CotaTVA] [decimal](5, 2) NOT NULL DEFAULT 0,
		[IDTipDocument] [smallint] NOT NULL DEFAULT 0,
		[TotalValoare] [decimal](25, 5) NOT NULL DEFAULT 0,
		[TotalValoareTVA] [decimal](25, 5) NOT NULL DEFAULT 0,
		[Total] [decimal](25, 5) NOT NULL DEFAULT 0,
		[IDRegimFiscal] [smallint] NOT NULL DEFAULT 0,
		[UserId] [uniqueidentifier] NULL,
		[IDDepartament] [int] NULL DEFAULT 0,
		[NrContract] [varchar](50) NULL,
		[DataContract] [datetime] NULL,
		[Observatii] [varchar](250) NULL,
		[DataScadenta] [datetime] NULL,
		[ValoareTotalaCuAdaos] [decimal](25, 5) NOT NULL DEFAULT 0,
		[NrDocReceptie] [varchar](20) NULL,
		[DataDocReceptie] [datetime] NULL,
		[IDGestionar] [int] NULL,
		[IDPredator] [int] NULL,
		[IDJurnal] [int] NULL,
		[CursValutar] [decimal](18, 4) NOT NULL,
		[CodValuta] [smallint] NOT NULL,
		[AreDocGestStoc] [bit] NOT NULL,
		[DataStartProductie] [datetime] NOT NULL,
	 CONSTRAINT [PK_Documente'+@strTabelaAn+'] PRIMARY KEY CLUSTERED 
	(
		[IDDocument] ASC
	),
	 CONSTRAINT [Dublare_Documente_Furnizor_Numar_Data'+@strTabelaAn+'] UNIQUE NONCLUSTERED 
	(
		[IDPartener] ASC,
		[CodUnitate] ASC,
		[NrDoc] ASC,
		[DataDoc] ASC
	),
	 CONSTRAINT [FK_Documente_Departamente'+@strTabelaAn+'] FOREIGN KEY ([IDDepartament]) REFERENCES [dbo].[Departamente] ([IDDepartament]),
	 CONSTRAINT [FK_Documente_Parteneri'+@strTabelaAn+'] FOREIGN KEY([IDPartener]) REFERENCES [dbo].[Parteneri] ([IDPartener]),
	 CONSTRAINT [FK_Documente_RegimFiscal'+@strTabelaAn+'] FOREIGN KEY([IDRegimFiscal]) REFERENCES [dbo].[RegimFiscal] ([IDRegimFiscal]),
	 CONSTRAINT [FK_Documente_TipDocument'+@strTabelaAn+'] FOREIGN KEY([IDTipDocument]) REFERENCES [dbo].[TipDocument] ([IDTipDocument]),
	 CONSTRAINT [FK_Documente_Unitati'+@strTabelaAn+'] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate]),
	 CONSTRAINT [FK_Documente_Jurnale'+@strTabelaAn+'] FOREIGN KEY([IDJurnal]) REFERENCES [dbo].[Jurnale] ([IDJurnal]),
	 CONSTRAINT [FK_Documente_Valuta'+@strTabelaAn+'] FOREIGN KEY([CodValuta]) REFERENCES [dbo].[Valuta] ([CodValuta]),
	 CONSTRAINT [FK_Documente_Gestionari'+@strTabelaAn+'] FOREIGN KEY([IDGestionar]) REFERENCES [dbo].[Gestionari] ([IDGestionar])
	) ON [PRIMARY]'
		
	IF @existTable = 0
		EXEC(@Comanda)
		

	SET @existTable = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE 'DocumenteDetaliu'+@strTabelaAn)
		SET @existTable = 1

	SET @Comanda = 'CREATE TABLE [dbo].[DocumenteDetaliu'+@strTabelaAn+'](
		[IDDocumentDetaliu] [bigint] NOT NULL,
		[IDDocument] [bigint] NOT NULL,
		[IDArticol] [int] NOT NULL,
		[Cantitate] [decimal](25, 5) NOT NULL DEFAULT 0,
		[ValoareUnitara] [decimal](25, 5) NOT NULL  DEFAULT 0,
		[ValoareTVA] [decimal](25, 5) NOT NULL  DEFAULT 0,
		[ValoareTotala] [decimal](25, 5) NOT NULL,
		[CodUnitate] [smallint] NOT NULL  DEFAULT 0,
		[IDUnitateMasura] [smallint] NOT NULL  DEFAULT 0,
		[IDRegimFiscal] [smallint] NOT NULL  DEFAULT 0,
		[CotaTVA] [decimal](5, 2) NOT NULL DEFAULT 0,
		[TermenLivrare] [datetime] NULL,
		[IDVariantaArticol] [int] NULL,
		[Observatii] [varchar](250) NULL,
		[ValoareTotalaCuAdaos] [decimal](25, 5) NOT NULL DEFAULT 0,
		[ArtAl] [varchar](40) NULL,
		[ValoareUnitaraValuta] [decimal](25, 5) NOT NULL,
	 CONSTRAINT [PK_DocumenteDetaliu'+@strTabelaAn+'] PRIMARY KEY CLUSTERED 
	(
		[IDDocumentDetaliu] ASC
	),
	CONSTRAINT [FK_DocumenteDetaliu_Articole'+@strTabelaAn+'] FOREIGN KEY([IDArticol]) REFERENCES [dbo].[Articole] ([IDArticol]),
	CONSTRAINT [FK_DocumenteDetaliu_ArticoleVariante'+@strTabelaAn+'] FOREIGN KEY([IDVariantaArticol])REFERENCES [dbo].[ArticoleVariante] ([IDVariantaArticol]),
	CONSTRAINT [FK_DocumenteDetaliu_Documente'+@strTabelaAn+'] FOREIGN KEY([IDDocument]) REFERENCES [dbo].[Documente'+@strTabelaAn+'] ([IDDocument]),
	CONSTRAINT [FK_DocumenteDetaliu_RegimFiscal'+@strTabelaAn+'] FOREIGN KEY([IDRegimFiscal]) REFERENCES [dbo].[RegimFiscal] ([IDRegimFiscal]),
	CONSTRAINT [FK_DocumenteDetaliu_Unitati'+@strTabelaAn+'] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate]),
	CONSTRAINT [FK_DocumenteDetaliu_UnitatiMasura'+@strTabelaAn+'] FOREIGN KEY([IDUnitateMasura]) REFERENCES [dbo].[UnitatiMasura] ([IDUnitateMasura]),
	) ON [PRIMARY]'
	
	IF @existTable = 0
		EXEC(@Comanda)
		
	SET @existTable = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE 'DocumentePlata'+@strTabelaAn)
		SET @existTable = 1

	SET @Comanda = 'CREATE TABLE [dbo].[DocumentePlata'+@strTabelaAn+'](
		[IDDocumentPlata] [int] NOT NULL,
		[Numar] [varchar](20) NOT NULL,
		[Data] [datetime] NOT NULL,
		[IDTipPlata] [smallint] NOT NULL,
		[ValoareTotala] [decimal](18, 2) NOT NULL DEFAULT 0,
		[IDPartener] [bigint] NOT NULL,
		[Reprezentand] [varchar](250) NULL,
		[TipOperatiune] [varchar](10) NOT NULL DEFAULT (''INC''),
		[CodUnitate] [smallint] NOT NULL DEFAULT 0,
		[DataExtras] [datetime] NULL,
		[IDOrdonantare] [int] NULL,
	 CONSTRAINT [PK_DocumentePlata'+@strTabelaAn+'] PRIMARY KEY CLUSTERED 
	(
		[IDDocumentPlata] ASC
	),
	CONSTRAINT [FK_DocumentePlata'+@strTabelaAn+'_Parteneri] FOREIGN KEY([IDPartener]) REFERENCES [dbo].[Parteneri] ([IDPartener]),
	CONSTRAINT [FK_DocumentePlata'+@strTabelaAn+'_TipDocumentPlata] FOREIGN KEY([IDTipPlata]) REFERENCES [dbo].[TipDocumentPlata] ([IDTipPlata]),
	CONSTRAINT [FK_DocumentePlata'+@strTabelaAn+'_Unitati] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])
	) ON [PRIMARY]'

	IF @existTable = 0
		EXEC(@Comanda)
		
	SET @existTable = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE 'DocumentePlataDetaliu'+@strTabelaAn)
		SET @existTable = 1

	SET @Comanda = 'CREATE TABLE [dbo].[DocumentePlataDetaliu'+@strTabelaAn+'](
		[IDDocPlataDetaliu] [int] NOT NULL,
		[IDDocument] [bigint] NULL,
		[IDDocumentPlata] [int] NOT NULL,
		[Valoare] [decimal](18, 2) NOT NULL DEFAULT 0,
	 CONSTRAINT [PK_DocumentePlataDetaliu'+@strTabelaAn+'] PRIMARY KEY CLUSTERED 
	(
		[IDDocPlataDetaliu] ASC
	),
		CONSTRAINT [FK_DocumentePlataDetaliu'+@strTabelaAn+'_DocumentePlata'+@strTabelaAn+'] FOREIGN KEY([IDDocumentPlata]) REFERENCES [dbo].[DocumentePlata'+@strTabelaAn+'] ([IDDocumentPlata]),
	) ON [PRIMARY]'

	IF @existTable = 0
			EXEC(@Comanda)
			
	SET @existTable = 0
	IF  EXISTS (SELECT * FROM sysobjects WHERE id =  OBJECT_ID(N'[dbo].[fares_DocumentePlatite'+@strTabelaAn+']'))
		SET @existTable = 1

	SET @Comanda = 'CREATE VIEW [dbo].[fares_DocumentePlatite'+@strTabelaAn+']
			AS
	SELECT     a.IDDocPlataDetaliu, a.IDDocumentPlata, a.Valoare, 
						  b.NrDoc + ''/'' + CONVERT(varchar(20), b.DataDoc, 101) AS NrDataDoc, a.IDDocument
	FROM         dbo.DocumentePlataDetaliu'+@strTabelaAn+' a INNER JOIN
						  dbo.Documente'+@strTabelaAn+'  b ON a.IDDocument = b.IDDocument'		
    IF @existTable = 0
			EXEC(@Comanda)
		
END		
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SeriiNumerice' AND COLUMN_NAME = 'Serie')
BEGIN
	ALTER TABLE dbo.SeriiNumerice ADD Serie varchar(10) NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'IDSerieFACT')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD IDSerieFACT nvarchar(20) NULL 
	ALTER TABLE [dbo].FaresSetup  WITH CHECK ADD  CONSTRAINT [FK_FaresSetup_SeriiNumerice_Factura] FOREIGN KEY([IDSerieFACT],[CodUnitate]) REFERENCES [dbo].[SeriiNumerice] ([IDSerie],[CodUnitate])
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'Serie')
BEGIN
	ALTER TABLE dbo.Documente ADD Serie varchar(10) NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'Numar')
BEGIN
	ALTER TABLE dbo.Documente ADD Numar varchar(20) NULL 
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ActSeriiNumerice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ActSeriiNumerice]
GO

CREATE PROCEDURE [dbo].[ActSeriiNumerice] 
	-- Add the parameters for the stored procedure here
	@IDSerie varchar(20),@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @UltNr varchar(20);
	DECLARE @StartNr varchar(20);
	DECLARE @DecUltNr decimal(18,0)
	DECLARE @DecStartNr decimal(18,0)
	DECLARE @Prefix varchar(20)
	SET @UltNr = '1'
	SELECT @StartNr = NrStart,@UltNr = UltimulNrFolosit FROM [SeriiNumerice] WHERE [CodUnitate]=@CodUnitate AND [IdSerie]=@IdSerie		

	IF @StartNr is null
		RETURN
	SET @DecUltNr = CAST(@UltNr AS DECIMAL(18,0))
	SET @Prefix = LTRIM(RTRIM(SUBSTRING(@UltNr,1, LEN(@UltNr)-LEN(RTRIM(LTRIM(CAST(@DecUltNr AS VARCHAR(20))))))))
	SET @DecStartNr = CAST(@StartNr AS DECIMAL(18,0))
	

    -- Insert statements for procedure here
	UPDATE [SeriiNumerice] SET UltimulNrFolosit = @Prefix + LTRIM(RTRIM(CAST(CASE WHEN @DecUltNr>@DecStartNr THEN @DecUltNr + 1 ELSE @DecStartNr+1 END  AS VARCHAR(20)))),
		[UltimaDataFolosit]  = GETDATE() WHERE [CodUnitate]=@CodUnitate AND [IdSerie]=@IdSerie		
END

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_GetPlatiDocument]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_GetPlatiDocument]
GO

CREATE PROCEDURE [dbo].[fares_GetPlatiDocument]
	@IDDocument bigint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	SELECT * FROM DocumentePlata dp 
	WHERE EXISTS(SELECT * FROM DocumentePlataDetaliu ddp WHERE ddp.IDDocument = @IDDocument AND dp.IDDocumentPlata=ddp.IDDocumentPlata)

END

GO


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewDetaliuPlata]'))
DROP VIEW [dbo].[fares_viewDetaliuPlata]
GO


CREATE VIEW [dbo].[fares_viewDetaliuPlata]
AS
SELECT     dbo.DocumentePlataDetaliu.IDDocPlataDetaliu, dbo.Documente.NrDoc, dbo.Documente.DataDoc, dbo.DocumentePlataDetaliu.IDDocumentPlata, 
                      dbo.Documente.IDDocument
FROM         dbo.DocumentePlataDetaliu LEFT OUTER JOIN
                      dbo.Documente ON dbo.DocumentePlataDetaliu.IDDocument = dbo.Documente.IDDocument

GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumentePlata' AND COLUMN_NAME = 'Serie')
BEGIN
	ALTER TABLE dbo.DocumentePlata ADD Serie varchar(10) NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumentePlata' AND COLUMN_NAME = 'Numar')
BEGIN
	ALTER TABLE dbo.DocumentePlata ADD Numar varchar(20) NULL 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'IDSerieCHIT')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD IDSerieCHIT nvarchar(20) NULL 
	ALTER TABLE [dbo].FaresSetup  WITH CHECK ADD  CONSTRAINT [FK_FaresSetup_SeriiNumerice_Chitanta] FOREIGN KEY([IDSerieCHIT],[CodUnitate]) REFERENCES [dbo].[SeriiNumerice] ([IDSerie],[CodUnitate])
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaListaRulaje]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaListaRulaje]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaListaRulaje] 
	@filtruPart varchar(8000),
	@filtruArt varchar(8000),
	@filtruCat varchar(8000),
	@filtruTip varchar(800),
	@delaData datetime,
	@laData datetime,
	@StocuriZero bit,
	@Comparatie smallint,
	@ValoareStoc decimal(25,5),
	@CodUnitate smallint
AS
BEGIN
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    SELECT * FROM
    (SELECT  td.Denumire+'('+td.TipOperatie + ')' Denumire, art.IDArticol,docDet.ValoareUnitara,doc.IDDocument,
    art.Denumire DenumireArticol,tca.Denumire DenumireCategorie, 
    part.Denumire DenumirePartener,um.Denumire DenumireUM,
    doc.DataDoc,doc.NrDoc,docDet.Cantitate,docDet.ValoareTotala,docDet.ValoareTVA,Coalesce(doc.NrDocReceptie,'') NrDocReceptie,doc.DataDocReceptie,
    td.IDTipDocument
    FROM [Articole] art
    LEFT OUTER JOIN [DocumenteDetaliu] docDet ON docDet.IDArticol = art.IDArticol
    JOIN [Documente] doc ON doc.IDDocument = docDet.IDDocument
    JOIN [TipDocument] td ON doc.IDTipDocument = td.IDTipDocument
    JOIN [Parteneri] part ON doc.IDPartener = part.IDPartener
    JOIN [TipCategoriiArticole] tca ON art.IDCategorie = tca.IDCategorie
    JOIN UnitatiMasura um ON art.IDUnitateMasura = um.IDUnitateMasura
    WHERE 
    art.CodUnitate = @CodUnitate AND doc.DataDoc >=@delaData and doc.DataDoc<=@laData AND
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (art.IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (part.IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruCat)))=0 OR (tca.IDCategorie IN (SELECT CAST(fart.value as smallint) FROM dbo.SplitParameters(@filtruCat,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruTip)))=0 OR (td.IDTipDocument IN (SELECT CAST(fart.value as smallint) FROM dbo.SplitParameters(@filtruTip,',') fart))) 
    )
    v
     
END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[admin_DocumenteDisponibile]'))
DROP VIEW [dbo].[admin_DocumenteDisponibile]
GO

CREATE VIEW [dbo].[admin_DocumenteDisponibile]
AS
SELECT     dbo.admin_ApplicationDocuments.ApplicationID, dbo.TipDocument.Denumire, dbo.TipDocument.TipOperatie, dbo.TipDocument.IDTipDocument, 
                      dbo.TipDocument.ModificaStoc, dbo.TipDocument.SePlateste
FROM         dbo.admin_ApplicationDocuments INNER JOIN
                      dbo.TipDocument ON dbo.admin_ApplicationDocuments.IDTipDocument = dbo.TipDocument.IDTipDocument

GO


DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9' and [Name]='Fisa de Magazie'
IF @Cate= 0 
begin
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(4853,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Fisa de Magazie',4850,23,'Lista_FisaMagazie',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 
go



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TipProgrameSanatate]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TipProgrameSanatate](
		[IDTipProgram] [smallint] IDENTITY(1,1) NOT NULL,
		[DenumireProgram] [varchar](50) NOT NULL,
	 CONSTRAINT [PK_TipProgramSanatate] PRIMARY KEY CLUSTERED 
	(
		[IDTipProgram] ASC
	)
	) ON [PRIMARY]
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'IDProgramSanatate')
BEGIN
	ALTER TABLE dbo.Documente ADD IDProgramSanatate smallint NULL
	ALTER TABLE dbo.Documente ADD CONSTRAINT FK_Documente_ProgrameSanatate FOREIGN KEY (IDProgramSanatate) REFERENCES dbo.TipProgrameSanatate(IDTipProgram) 	
END
go

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9' and [HandlerName]='TipProgrameSanatate'
IF @Cate= 0 
begin
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(3415,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Programe Sanatate',3400,34,'TipProgrameSanatate',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 
go

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'PretAchizitie')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu ADD PretAchizitie decimal(25,5) NULL 
END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewDocumenteTipuriDetalii]'))
DROP VIEW [dbo].[fares_viewDocumenteTipuriDetalii]
GO

CREATE VIEW [dbo].[fares_viewDocumenteTipuriDetalii]
AS
SELECT     dbo.Documente.IDDocument, dbo.Documente.NrDoc, dbo.Documente.DataDoc, dbo.Documente.IDPartener, dbo.Documente.CodUnitate, dbo.Documente.CotaTVA, 
                      dbo.Documente.IDTipDocument, dbo.Documente.TotalValoare, dbo.Documente.TotalValoareTVA, dbo.Documente.Total, dbo.Documente.IDRegimFiscal, 
                      dbo.Documente.UserId, dbo.Documente.IDDepartament, dbo.Documente.NrContract, dbo.Documente.DataContract, dbo.Documente.Observatii, 
                      dbo.Documente.DataScadenta, dbo.Documente.ValoareTotalaCuAdaos, dbo.Documente.NrDocReceptie, dbo.Documente.DataDocReceptie, 
                      dbo.Documente.IDGestionar, dbo.Documente.IDPredator, dbo.Documente.IDJurnal, dbo.Documente.CursValutar, dbo.Documente.CodValuta, 
                      dbo.TipDocument.TipOperatie, DocumenteDetaliu.IDArticol, DocumenteDetaliu.PretAchizitie
FROM         dbo.Documente INNER JOIN
                      dbo.TipDocument ON dbo.Documente.IDTipDocument = dbo.TipDocument.IDTipDocument INNER JOIN
                          (SELECT DISTINCT IDArticol, IDDocument, PretAchizitie
                            FROM          dbo.DocumenteDetaliu AS DocumenteDetaliu_1) AS DocumenteDetaliu ON dbo.Documente.IDDocument = DocumenteDetaliu.IDDocument

GO

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [TipDocument] WHERE [IDTipDocument]=15
IF @Cate= 0 
BEGIN
	SET IDENTITY_INSERT [TipDocument] ON
	INSERT INTO [tipDocument] ([IDTipDocument],[Denumire],[TipOperatie],[SePlateste],[ModificaStoc] )VALUES(15,'Receptie','I',0,1)           
	SET IDENTITY_INSERT [TipDocument] OFF
END
GO

DECLARE @Cate3 int
SELECT @Cate3 = COUNT(*) FROM [admin_ApplicationDocuments] WHERE [IDTipDocument]=15
IF @Cate3= 0 
BEGIN
INSERT INTO [admin_ApplicationDocuments] ([IDTipDocument],[ApplicationID])VALUES(15,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9')
END
GO


DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9' and [HandlerName]='TipProgrameSanatate'
IF @Cate= 0 
begin
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(3415,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Programe Sanatate',3400,34,'TipProgrameSanatate',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 
go

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'DataCreation')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu ADD DataCreation datetime NOT NULL DEFAULT(getdate())
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'DataCreation')
BEGIN
	ALTER TABLE dbo.Documente ADD DataCreation datetime NOT NULL DEFAULT(getdate())
END
GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaListaFisaMagazie]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaListaFisaMagazie]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaListaFisaMagazie] 
	-- Add the parameters for the stored procedure here
	@filtruArt varchar(8000),
	@laData datetime,
	@CodUnitate smallint
AS
BEGIN
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    SELECT * FROM
    (SELECT  td.Denumire+'('+td.TipOperatie + ')' Denumire, art.IDArticol,docDet.PretAchizitie,doc.IDDocument,
    art.Denumire DenumireArticol,um.Denumire DenumireUM,
    doc.DataDoc,doc.NrDoc,
    case when td.TipOperatie='I' then docDet.Cantitate else 0 end Intrari,
    case when td.TipOperatie='O' then docDet.Cantitate else 0 end Iesiri,
    coalesce((select SUM(s.StocInitial+s.StocPrecedent) FROM Stocuri s where s.IDArticol=docDet.IDArticol and s.Pret = docDet.PretAchizitie),0)
    + Coalesce((Select SUM(Cantitate) FROM DocumenteDetaliu dd JOIN Documente dct on dd.IDDocument=dct.IDDocument
    join TipDocument tipd ON dct.IDTipDocument = tipd.IDTipDocument
     where dd.IDArticol = docDet.IDArticol AND dd.PretAchizitie =docDet.PretAchizitie and dct.DataCreation<=doc.DataCreation
     and tipd.TipOperatie='I' and tipd.ModificaStoc=1 AND dct.AreDocGestStoc=1),0) 
     - Coalesce((Select SUM(Cantitate) FROM DocumenteDetaliu dd JOIN Documente dct on dd.IDDocument=dct.IDDocument
    join TipDocument tipd ON dct.IDTipDocument = tipd.IDTipDocument
     where dd.IDArticol = docDet.IDArticol AND dd.PretAchizitie =docDet.PretAchizitie and dct.DataCreation<=doc.DataCreation
     and tipd.TipOperatie='O' and tipd.ModificaStoc=1 AND dct.AreDocGestStoc=1),0)
     stoc,
    docDet.ValoareTotala,docDet.ValoareTVA,Coalesce(doc.NrDocReceptie,'') NrDocReceptie,doc.DataDocReceptie,
    td.IDTipDocument,coalesce(art.Lungime,0) Lungime,coalesce(art.Latime,0) Latime,Coalesce(art.Grosime,0) Grosime,Coalesce(art.Greutate,0) Greutate,
	doc.DataCreation
    FROM [Articole] art
    LEFT OUTER JOIN [DocumenteDetaliu] docDet ON docDet.IDArticol = art.IDArticol
    JOIN [Documente] doc ON doc.IDDocument = docDet.IDDocument
    JOIN [TipDocument] td ON doc.IDTipDocument = td.IDTipDocument AND td.ModificaStoc=1
    JOIN UnitatiMasura um ON art.IDUnitateMasura = um.IDUnitateMasura
    WHERE 
    art.CodUnitate = @CodUnitate AND doc.AreDocGestStoc=1 AND
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (art.IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart)))
    )
    v
END

GO

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [TipDocument] WHERE [IDTipDocument]=9 
IF @Cate= 1 
begin
	UPDATE [TipDocument] SET [Denumire]='Comanda de cumparare' WHERE [IDTipDocument]=9 
end 
go

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [TipDocument] WHERE [IDTipDocument]=12 
IF @Cate= 1 
begin
	update [TipDocument] set [Denumire]='Comanda de vanzare' WHERE [IDTipDocument]=12
end 
go

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'ComandaFaraPreturi')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD ComandaFaraPreturi bit NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'TotalValoareValuta')
BEGIN
	ALTER TABLE dbo.Documente ADD TotalValoareValuta decimal(25,5) NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Parteneri' AND COLUMN_NAME = 'IDTara')
BEGIN
	ALTER TABLE dbo.Parteneri ADD IDTara int NULL 
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ArticolePreturi]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[ArticolePreturi](
		[IDArticolPret] [int] IDENTITY(1,1) NOT NULL,
		[IDArticol] [int] NOT NULL,
		[IDPartener] [bigint] NOT NULL,
		[PretVanzare] [decimal](25, 2) NOT NULL,
		[CodValuta] [smallint] NOT NULL,
		[DataAplicare] [datetime] NOT NULL DEFAULT (getdate()),
		[NrMinimArticole] [int] NULL,
		[NrMaximArticole] [int] NULL,
		[Observatii] [varchar](250) NULL,
	 CONSTRAINT [PK_ArticolePreturi] PRIMARY KEY CLUSTERED ([IDArticolPret] ASC),
	 CONSTRAINT [FK_ArticolePreturi_Articole] FOREIGN KEY([IDArticol]) REFERENCES [dbo].[Articole] ([IDArticol]),
	 CONSTRAINT [FK_ArticolePreturi_Parteneri] FOREIGN KEY([IDPartener]) REFERENCES [dbo].[Parteneri] ([IDPartener]),
	 CONSTRAINT [FK_ArticolePreturi_Valuta] FOREIGN KEY([CodValuta]) REFERENCES [dbo].[Valuta] ([CodValuta])
	) ON [PRIMARY]

END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Judete' AND COLUMN_NAME = 'IDTara')
BEGIN
	ALTER TABLE dbo.Judete ADD IDTara int NULL 
	ALTER TABLE dbo.Judete ADD CONSTRAINT FK_Judete_Tari FOREIGN KEY (IDTara) REFERENCES dbo.Tari(IDTara) 	
END
GO

UPDATE Judete SET IDTara = 538
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewSumeCategorii]'))
DROP VIEW [dbo].[fares_viewSumeCategorii]
GO

CREATE VIEW [dbo].[fares_viewSumeCategorii]
AS
SELECT     dbo.TipCategoriiArticole.Denumire, dbo.Documente.DataDoc, SUM(dbo.DocumenteDetaliu.ValoareTotala) AS ValoareTotala, dbo.DocumenteDetaliu.CodUnitate, 
                      dbo.Articole.Denumire AS DenumireArticol, dbo.Departamente.Nume AS DenDepartament, dbo.Jurnale.Denumire AS DenumireJurnal, dbo.Documente.IDPartener, 
                      dbo.Articole.IDArticol, dbo.Documente.IDTipDocument
FROM         dbo.Articole INNER JOIN
                      dbo.DocumenteDetaliu ON dbo.Articole.IDArticol = dbo.DocumenteDetaliu.IDArticol INNER JOIN
                      dbo.TipCategoriiArticole ON dbo.Articole.IDCategorie = dbo.TipCategoriiArticole.IDCategorie INNER JOIN
                      dbo.Documente ON dbo.DocumenteDetaliu.IDDocument = dbo.Documente.IDDocument LEFT OUTER JOIN
                      dbo.Departamente ON dbo.Documente.IDDepartament = dbo.Departamente.IDDepartament LEFT OUTER JOIN
                      dbo.Jurnale ON dbo.Departamente.IDJurnal = dbo.Jurnale.IDJurnal
WHERE     (dbo.Documente.IDTipDocument = 9)
GROUP BY dbo.TipCategoriiArticole.Denumire, dbo.Documente.DataDoc, dbo.DocumenteDetaliu.CodUnitate, dbo.Articole.Denumire, dbo.Departamente.Nume, 
                      dbo.Jurnale.Denumire, dbo.Documente.IDPartener, dbo.Documente.CodUnitate, dbo.Articole.IDArticol, dbo.Documente.IDTipDocument

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportArticoleComanda]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportArticoleComanda]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaRaportArticoleComanda] 
	@filtruPart varchar(8000),
	@filtruArt varchar(8000),
	@data1 datetime,
	@data2 datetime,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	SELECT * FROM [fares_viewSumeCategorii] WHERE 
	(LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
	[DataDoc]>=@data1 AND [DataDoc]<= @data2 AND CodUnitate = @CodUnitate
	 ORDER BY [DataDoc]

END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportDocumenteTVA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportDocumenteTVA]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaRaportDocumenteTVA] 
    @filtruPart varchar(8000),
	@filtruArt varchar(8000),
	@data1 datetime,
	@data2 datetime,
	@DefalcatTVA bit,
	@receptie bit,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	SELECT * FROM [fares_DocumenteTVADimensiuni] WHERE 
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
    (@receptie=0 OR (@receptie=1 AND [TipOperatie] LIKE '%I%' AND IDTipDocument=0)) AND
    ([ValoareTotalaCuAdaos24]<>0 OR [ValoareTotalaCuAdaos9]<>0) AND 
	CodUnitate = @CodUnitate AND [DataDoc]>=@data1 AND [DataDoc]<=@data2
	ORDER BY [DataDoc]

END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportDocumente]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportDocumente]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaRaportDocumente] 
    @filtruPart varchar(8000),
	@filtruArt varchar(8000),
	@data1 datetime,
	@data2 datetime,
	@DefalcatTVA bit,
	@receptie bit,
	@marfa bit,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

  SELECT * FROM [fares_DocumenteDimensiuni] WHERE 
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
    (@receptie=0 OR (@receptie=1 AND [TipOperatie] LIKE '%I%' AND IDTipDocument=0)) AND
    ((@marfa=0 AND [ValoareTotalaCuAdaos]=0) OR (@marfa=1 AND [ValoareTotalaCuAdaos]<>0)) AND 
	CodUnitate = @CodUnitate AND [DataDoc]>=@data1 AND [DataDoc]<=@data2
	ORDER BY [DataDoc]
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportOpConturi]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportOpConturi]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaRaportOpConturi] 
    @filtruPart varchar(8000),
	@filtruArt varchar(8000),
	@data1 datetime,
	@data2 datetime,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

  SELECT * FROM [fares_DocumenteDimConturi] WHERE 
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
 	CodUnitate = @CodUnitate AND [DataDoc]>=@data1 AND [DataDoc]<=@data2
	ORDER BY [DataDoc]
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportFacturi]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportFacturi]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaRaportFacturi] 
    @filtruPart varchar(8000),
    @filtruDoc varchar(8000),
	@data1 datetime,
	@data2 datetime,
	@datasold datetime,
	@facturiSold bit,
	@totalNeachitate bit,
	@integralAchitate bit,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	SELECT * FROM 
	(SELECT     a.IDPartener, a.NrDoc, a.DataDoc, ROUND(a.Total, 2) AS Total, ROUND(a.TotalValoare, 2) AS TotalValoare, ROUND(a.TotalValoareTVA, 2) AS TotalValoareTVA, COALESCE (b.Valoare, 0) AS Valoare, ROUND(a.Total, 2) - COALESCE (b.Valoare, 0) AS RestPlata, 
               a.DataScadenta, dbo.Parteneri.Denumire, a.IDTipDocument, a.CodUnitate, cast(a.IDDocument AS Varchar(50)) AS IDDocument
		FROM         dbo.Documente AS a LEFT OUTER JOIN
                          (SELECT     IDDocument, SUM(Valoare) AS Valoare
                            FROM          dbo.DocumentePlataDetaliu dpd JOIN DocumentePlata dp ON dpd.IDDocumentPlata=dp.IDDocumentPlata WHERE Data<=@datasold
                            GROUP BY IDDocument ) AS b ON a.IDDocument = b.IDDocument INNER JOIN
                      dbo.Parteneri ON a.IDPartener = dbo.Parteneri.IDPartener) a WHERE 
     (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND           
     (LEN(LTRIM(RTRIM(@filtruDoc)))=0 OR (IDTipDocument IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruDoc,',') fart))) AND
	 CodUnitate = @CodUnitate AND [DataDoc]>=@data1 AND [DataDoc]<=@data2 AND
	 (@facturiSold=0 OR (@facturiSold=1 AND [RestPlata] <> 0)) AND
	 (@totalNeachitate=0 OR (@totalNeachitate=1 AND [RestPlata] = [Total])) AND 
	 (@integralAchitate=0 OR (@integralAchitate=1 AND  [RestPlata] = [Valoare]))
	 
	 ORDER BY [DataDoc]

END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportPlati]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportPlati]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaRaportPlati] 
    @filtruPart varchar(8000),
	@filtruDocPlata varchar(8000),
	@data1 datetime,
	@data2 datetime,
	@numaiAvansuri bit,
	@documenteCLB smallint,
	@perioadaFactura bit,
	@data1p datetime,
	@data2p datetime,	
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

  SELECT * FROM [fares_Plati] WHERE 
    (LEN(LTRIM(RTRIM(@filtruDocPlata)))=0 OR (IDTipPlata IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruDocPlata,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
 	CodUnitate = @CodUnitate AND [Data]>=@data1 AND [Data]<=@data2 AND
 	(@numaiAvansuri=0 OR (@numaiAvansuri=1 AND [NrDoc] is NULL)) AND
 	((@documenteCLB=0 AND [TipOperatiune]='I') OR (@documenteCLB=1 AND [TipOperatiune]='O')) AND
 	(@perioadaFactura=0 OR (@perioadaFactura=1 AND [DataDoc]>=@data1p AND [DataDoc]<=@data2p))
	ORDER BY [DataDoc]
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportFisaPartenerului]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportFisaPartenerului]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaRaportFisaPartenerului] 
    @filtruPart varchar(8000),
    @filtruDoc varchar(8000),
	@data1 datetime,
	@data2 datetime,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

  SELECT * FROM [fares_FisaPartenerului] WHERE 
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruDoc)))=0 OR (IDTipDocument IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruDoc,',') fart))) AND
 	CodUnitate = @CodUnitate AND [DataDoc]>=@data1 AND [DataDoc]<=@data2
END


GO


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[onco_ViewLocalizareProtocolAll]'))
DROP VIEW [dbo].[onco_ViewLocalizareProtocolAll]
GO

CREATE VIEW [dbo].[onco_ViewLocalizareProtocolAll]
AS
SELECT     0 AS IDLocalizare, 0 AS IDLocalizareProtocol, dbo.onco_Protocoale.Durata, dbo.onco_Protocoale.NumarDeZile, 
                      dbo.onco_Protocoale.Denumire, dbo.onco_Protocoale.ZileCiclu, dbo.onco_Protocoale.Punctaj, dbo.onco_Protocoale.Observatii, 
                      dbo.onco_Protocoale.NumarDeZileTratament, dbo.onco_Protocoale.CIM10, dbo.onco_Protocoale.IDProtocol, dbo.onco_Protocoale.IDDurataPerfuzie, 
                      dbo.onco_Protocoale.IDProcedura, dbo.onco_Protocoale.Activ
FROM      dbo.onco_Protocoale 



GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewArticoleComanda]'))
DROP VIEW [dbo].[fares_viewArticoleComanda]
GO

CREATE VIEW [dbo].[fares_viewArticoleComanda]
AS
SELECT     dbo.Articole.Denumire, dbo.ArticoleParteneri.CodArticol, dbo.Articole.CodArticol AS MyCodArticol, dbo.Documente.IDDocument, dbo.Articole.CodCPV, 
                      dbo.UnitatiMasura.Denumire AS UM, dbo.DocumenteDetaliu.Cantitate, dbo.DocumenteDetaliu.ValoareUnitara, dbo.DocumenteDetaliu.IDArticol, 
                      dbo.DocumenteDetaliu.Cantitate * dbo.DocumenteDetaliu.ValoareUnitara AS ValoareTotala, dbo.DocumenteDetaliu.TermenLivrare, 
                      dbo.DocumenteDetaliu.IDDocumentDetaliu, dbo.ArticoleVariante.Denumire AS Varianta, dbo.DocumenteDetaliu.Observatii, dbo.DocumenteDetaliu.ValoareTVA, 
                      dbo.DocumenteDetaliu.ValoareUnitaraValuta
FROM         dbo.DocumenteDetaliu INNER JOIN
                      dbo.Articole ON dbo.DocumenteDetaliu.IDArticol = dbo.Articole.IDArticol INNER JOIN
                      dbo.UnitatiMasura ON dbo.DocumenteDetaliu.IDUnitateMasura = dbo.UnitatiMasura.IDUnitateMasura INNER JOIN
                      dbo.Documente ON dbo.DocumenteDetaliu.IDDocument = dbo.Documente.IDDocument LEFT OUTER JOIN
                      dbo.ArticoleVariante ON dbo.DocumenteDetaliu.IDVariantaArticol = dbo.ArticoleVariante.IDVariantaArticol AND 
                      dbo.Articole.IDArticol = dbo.ArticoleVariante.IDArticol LEFT OUTER JOIN
                      dbo.ArticoleParteneri ON dbo.DocumenteDetaliu.IDArticol = dbo.ArticoleParteneri.IDArticol AND dbo.Documente.IDPartener = dbo.ArticoleParteneri.IDPartener

GO


IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DocumenteDetaliuLink]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[DocumenteDetaliuLink](
		[IDDocDetaliuLink] [bigint] IDENTITY(1,1) NOT NULL,
		[IDDocDetaliuSursa] [bigint] NOT NULL,
		[IDDocDetaliuDest] [bigint] NOT NULL,
	 CONSTRAINT [PK_DocumenteDetaliuLink] PRIMARY KEY CLUSTERED 
	(
		[IDDocDetaliuLink] ASC

	),
	CONSTRAINT [FK_DocumenteDetaliuLink_DocumenteDetaliu] FOREIGN KEY([IDDocDetaliuSursa])
	REFERENCES [dbo].[DocumenteDetaliu] ([IDDocumentDetaliu]),
	CONSTRAINT [FK_DocumenteDetaliuLink_DocumenteDetaliu1] FOREIGN KEY([IDDocDetaliuDest])
	REFERENCES [dbo].[DocumenteDetaliu] ([IDDocumentDetaliu])
	) ON [PRIMARY]
END
GO



IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'CantitateComandata')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu ADD
	CantComandata  AS dbo.GetCantitateComandataSiReceptionata(IDDocumentDetaliu,IDArticol) 
END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewComenziNeonorate]'))
DROP VIEW [dbo].[fares_viewComenziNeonorate]
GO


CREATE VIEW [dbo].[fares_viewComenziNeonorate]
AS
SELECT     IDDocumentDetaliu, IDArticol, Cantitate, ValoareUnitara, IDUnitateMasura, TermenLivrare, Observatii, ValoareUnitaraValuta, NrDoc, DataDoc, CodValuta, 
                      CantitateReceptionata, Cantitate - CantitateReceptionata AS CantitateRamasa, IDDocDetaliuDest, CodUnitate, IDPartener
FROM         (SELECT     dds.IDDocumentDetaliu, dds.IDArticol, dds.Cantitate, dds.ValoareUnitara, dds.IDUnitateMasura, dds.TermenLivrare, dds.Observatii, 
                                              dds.ValoareUnitaraValuta, ds.NrDoc, ds.DataDoc, ds.CodValuta, ds.CodUnitate, ds.IDPartener,
                                                  (SELECT     COALESCE (SUM(ddr.Cantitate), 0) AS CantitateReceptionata
                                                    FROM          dbo.DocumenteDetaliu AS ddr INNER JOIN
                                                                           dbo.Documente AS dr ON dr.IDDocument = ddr.IDDocument INNER JOIN
                                                                           dbo.DocumenteDetaliuLink AS ddl ON ddr.IDDocumentDetaliu = ddl.IDDocDetaliuDest
                                                    WHERE      (ddr.IDArticol = dds.IDArticol) AND (dr.IDTipDocument IN (0, 15)) AND (dr.AreDocGestStoc = 1) AND 
                                                                           (ddl.IDDocDetaliuSursa = dds.IDDocumentDetaliu)) AS CantitateReceptionata, ddl2.IDDocDetaliuDest
                       FROM          dbo.DocumenteDetaliu AS dds INNER JOIN
                                              dbo.Documente AS ds ON ds.IDDocument = dds.IDDocument AND ds.IDTipDocument = 9 LEFT OUTER JOIN
                                              dbo.DocumenteDetaliuLink AS ddl2 ON ddl2.IDDocDetaliuSursa = dds.IDDocumentDetaliu) AS t1

GO

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[audit_aspnet_Membership]'))
DROP TRIGGER [dbo].[audit_aspnet_Membership]
GO

CREATE TRIGGER [dbo].[audit_aspnet_Membership] 
   ON  [dbo].[aspnet_Membership]
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    INSERT INTO [admin_Audit]
           ([UserId]
           ,[TableName]
           ,[Operation]
           ,[CampID]
		   ,[CampIDStr]
           ,[Data])
     SELECT [UserIDUpdate],'aspnet_Membership', 'A', 0,cast(UserID as varchar(50)), getdate() FROM inserted i
		WHERE i.UserId not in (SELECT UserID from deleted)	AND i.[UserIDUpdate] is not null 

    INSERT INTO [admin_Audit]
           ([UserId]
           ,[TableName]
           ,[Operation]
           ,[CampID]
		   ,[CampIDStr]
           ,[Data])
     SELECT i.[UserIDUpdate],'aspnet_Membership', 'M', 0,cast(i.UserID as varchar(50)), getdate() FROM inserted i
		JOIN deleted d on i.UserId=d.UserId AND i.[UserIDUpdate] is not null 

    INSERT INTO [admin_Audit]
           ([UserId]
           ,[TableName]
           ,[Operation]
           ,[CampID]
		   ,[CampIDStr]
           ,[Data])
     SELECT [UserIDUpdate],'aspnet_Membership', 'D', 0,cast(UserID as varchar(50)), getdate() FROM deleted d
		WHERE d.UserId not in (SELECT UserId from inserted)	 AND d.[UserIDUpdate] is not null  

	

END

GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'ProdusePePartener')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD ProdusePePartener bit NOT NULL DEFAULT 0
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_GetArticolePartener]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_GetArticolePartener]
GO

CREATE PROCEDURE [dbo].[fares_GetArticolePartener]
	@IDPartener bigint
AS
BEGIN
	SET NOCOUNT ON;

	SELECT * FROM Articole a JOIN ArticolePreturi ap ON a.IDArticol = ap.IDArticol
	WHERE ap.IDPartener = @IDPartener
END

GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'DenumireNumeric1')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD DenumireNumeric1 varchar(50) NOT NULL DEFAULT 'Lungime'
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'DenumireNumeric2')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD DenumireNumeric2 varchar(50) NOT NULL DEFAULT 'Latime'
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'DenumireNumeric3')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD DenumireNumeric3 varchar(50) NOT NULL DEFAULT 'Inaltime'
END
GO




IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliuLink' AND COLUMN_NAME = 'Tip')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliuLink ADD Tip char(2) NOT NULL DEFAULT ('ST')
END
GO


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewComenziNeonorate]'))
DROP VIEW [dbo].[fares_viewComenziNeonorate]
GO

CREATE VIEW [dbo].[fares_viewComenziNeonorate]
AS

SELECT        IDDocumentDetaliu, IDArticol, Cantitate, ValoareUnitara, IDUnitateMasura, TermenLivrare, Observatii, ValoareUnitaraValuta, NrDoc, DataDoc, CodValuta, 
                         CantitateReceptionata, Cantitate - CantitateReceptionata AS CantitateRamasa, CodUnitate, IDPartener, IDTipDocument
FROM            (SELECT        dds.IDDocumentDetaliu, dds.IDArticol, dds.Cantitate, dds.ValoareUnitara, dds.IDUnitateMasura, dds.TermenLivrare, dds.Observatii, 
                                                    dds.ValoareUnitaraValuta, ds.NrDoc, ds.DataDoc, ds.CodValuta, ds.CodUnitate, ds.IDPartener, ds.IDTipDocument,
                                                        (SELECT        COALESCE (SUM(ddl.Cantitate), 0) AS CantitateReceptionata
                                                          FROM            dbo.DocumenteDetaliu AS ddr INNER JOIN
                                                                                    dbo.Documente AS dr ON dr.IDDocument = ddr.IDDocument INNER JOIN
                                                                                    dbo.DocumenteDetaliuLink AS ddl ON ddr.IDDocumentDetaliu = ddl.IDDocDetaliuDest AND 
                                                                                    ddl.IDDocDetaliuSursa = dds.IDDocumentDetaliu
                                                          WHERE        (dr.IDTipDocument IN (1, 13, 14, 0 ,15)) AND (dr.AreDocGestStoc = 1) AND ddl.Tip='CM') AS CantitateReceptionata
                          FROM            dbo.DocumenteDetaliu AS dds INNER JOIN
                                                    dbo.Documente AS ds ON ds.IDDocument = dds.IDDocument
                          WHERE        ds.IDTipDocument IN (9, 12)) AS t1


GO


IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'PretAchizitie')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu DROP COLUMN PretAchizitie
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliuLink' AND COLUMN_NAME = 'Cantitate')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliuLink ADD Cantitate decimal(25,5) NULL DEFAULT (0)
END
GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'CantComandata')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu DROP COLUMN CantComandata
END
GO

CREATE FUNCTION [dbo].[GetCantitateComandataSiReceptionata]
(
	@IDDocumentDetaliuReceptie bigint,
	@IDArticol int	
)
RETURNS decimal(25,5)
AS
BEGIN


DECLARE @ResultVar decimal(25,5)

	SELECT @ResultVar = COALESCE(SUM(ddl.Cantitate),0) FROM DocumenteDetaliu dd JOIN
	Documente d ON d.IDDocument=dd.IDDocument
	JOIN DocumenteDetaliuLink  ddl ON ddl.IDDocDetaliuSursa = dd.IDDocumentDetaliu
	AND ddl.IDDocDetaliuDest = @IDDocumentDetaliuReceptie AND dd.IDArticol=@IDArticol AND 
	(d.IDTipDocument = 9 OR d.IDTipDocument = 12) AND ddl.Tip='CM'

	-- Return the result of the function
	RETURN @ResultVar

END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'CantitateComandata')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu ADD
	CantComandata  AS dbo.GetCantitateComandataSiReceptionata(IDDocumentDetaliu,IDArticol) 
END
GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'StocIntrat')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu DROP COLUMN StocIntrat
END
GO


IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetCantitateStocIntrata]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[GetCantitateStocIntrata]
GO

CREATE FUNCTION [dbo].[GetCantitateStocIntrata]
(
	@IDDocumentDetaliuReceptie bigint,
	@IDArticol int	
)
RETURNS decimal(25,5)
AS
BEGIN

	DECLARE @ResultVar decimal(25,5)

	SELECT @ResultVar = COALESCE(SUM(ddl.Cantitate),0) FROM DocumenteDetaliu dd JOIN
	Documente d ON d.IDDocument=dd.IDDocument
	JOIN DocumenteDetaliuLink  ddl ON ddl.IDDocDetaliuSursa = dd.IDDocumentDetaliu
	AND ddl.IDDocDetaliuDest = @IDDocumentDetaliuReceptie AND dd.IDArticol=@IDArticol AND 
	(d.IDTipDocument = 0 OR d.IDTipDocument = 15) AND d.AreDocGestStoc=1 AND ddl.Tip='ST'

	-- Return the result of the function
	RETURN @ResultVar

END

GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'StocIntrat')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu ADD
	StocIntrat  AS dbo.GetCantitateStocIntrata(IDDocumentDetaliu,IDArticol) 
END
GO

CREATE TRIGGER [dbo].[Stoc_DocumenteDetaliu_Insert]
   ON  [dbo].[DocumenteDetaliu]
   AFTER INSERT,UPDATE,DELETE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	--SE ADAUGA POZITIA IN STOCURI FARA VALORI
	INSERT INTO Stocuri 
	([IDArticol],[CodUnitate],[Pret],[StocInitial],[StocPrecedent],[IDDepartament],[IDVarinataArticol],PretCodValuta,PretValuta)
	SELECT i.IDArticol, d.CodUnitate, i.ValoareUnitara,0,0,null,i.IDVariantaArticol,d.CodValuta,i.ValoareUnitaraValuta
	FROM inserted i JOIN  Documente d ON i.IDDocument = d.IDDocument JOIN TipDocument td ON td.IDTipDocument = d.IDTipDocument
	WHERE
	td.ModificaStoc=1 AND td.TipOperatie like '%I%' AND
	Not exists(SELECT * FROM Stocuri  s where s.IDArticol=i.IDArticol AND s.CodUnitate = d.CodUnitate AND s.Pret=i.ValoareUnitara and 
	((s.IDVarinataArticol = i.IDVariantaArticol) or ((s.IDVarinataArticol is null) and (i.IDVariantaArticol is null))))
	

END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewDocumenteStocuriIntrate]'))
DROP VIEW [dbo].[fares_viewDocumenteStocuriIntrate]
GO


CREATE VIEW [dbo].[fares_viewDocumenteStocuriIntrate]
AS
SELECT        IDDocumentDetaliu, IDArticol, Cantitate, ValoareUnitara, IDUnitateMasura, TermenLivrare, Observatii, ValoareUnitaraValuta, NrDoc, DataDoc, CodValuta, 
                         CantitateReceptionata, Cantitate - CantitateReceptionata AS CantitateRamasa, CodUnitate, IDPartener, IDTipDocument
FROM            (SELECT        dds.IDDocumentDetaliu, dds.IDArticol, dds.Cantitate, dds.ValoareUnitara, dds.IDUnitateMasura, dds.TermenLivrare, dds.Observatii, 
                                                    dds.ValoareUnitaraValuta, ds.NrDoc, ds.DataDoc, ds.CodValuta, ds.CodUnitate, ds.IDPartener, ds.IDTipDocument,
                                                        (SELECT        COALESCE (SUM(ddl.Cantitate), 0) AS CantitateReceptionata
                                                          FROM            dbo.DocumenteDetaliu AS ddr INNER JOIN
                                                                                    dbo.Documente AS dr ON dr.IDDocument = ddr.IDDocument INNER JOIN
                                                                                    dbo.DocumenteDetaliuLink AS ddl ON ddr.IDDocumentDetaliu = ddl.IDDocDetaliuDest AND 
                                                                                    ddl.IDDocDetaliuSursa = dds.IDDocumentDetaliu
                                                          WHERE        (dr.IDTipDocument IN (1, 13, 14)) AND (dr.AreDocGestStoc = 1) AND ddl.Tip='ST') AS CantitateReceptionata
                          FROM            dbo.DocumenteDetaliu AS dds INNER JOIN
                                                    dbo.Documente AS ds ON ds.IDDocument = dds.IDDocument
                          WHERE        (ds.IDTipDocument IN (0, 15)) AND (ds.AreDocGestStoc = 1)) AS t1

GO


IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__Stocuri__Intrari__58D39222]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Stocuri] DROP CONSTRAINT [DF__Stocuri__Intrari__58D39222]
END
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__Stocuri__Intrari__4B255CA0]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Stocuri] DROP CONSTRAINT DF__Stocuri__Intrari__4B255CA0
END
GO



IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Stocuri' AND COLUMN_NAME = 'Intrari')
BEGIN
	ALTER TABLE dbo.Stocuri DROP COLUMN Intrari
END
GO



IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__Stocuri__Iesiri__59C7B65B]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Stocuri] DROP CONSTRAINT [DF__Stocuri__Iesiri__59C7B65B]
END
GO

IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DF__Stocuri__Iesiri__4C1980D9]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[Stocuri] DROP CONSTRAINT DF__Stocuri__Iesiri__4C1980D9
END
GO





IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Stocuri' AND COLUMN_NAME = 'Iesiri')
BEGIN
	ALTER TABLE dbo.Stocuri DROP COLUMN Iesiri
END
GO


DROP FUNCTION [dbo].[GetStocIntrari]
GO


CREATE FUNCTION [dbo].[GetStocIntrari]
(
	@IDArticol int,
	@Pret decimal(25,5)	
)
RETURNS decimal(25,5)
AS
BEGIN

	DECLARE @ResultVar decimal(25,5)

	SELECT @ResultVar = COALESCE(SUM(dd.Cantitate),0) FROM DocumenteDetaliu dd JOIN
	Documente d ON d.IDDocument=dd.IDDocument 
	WHERE dd.IDArticol=@IDArticol AND dd.ValoareUnitara = @Pret AND 
	(d.IDTipDocument = 0 OR d.IDTipDocument = 15) AND d.AreDocGestStoc=1

	-- Return the result of the function
	RETURN @ResultVar

END

GO

DROP FUNCTION [dbo].[GetStocIesiri]
GO


CREATE FUNCTION [dbo].[GetStocIesiri]
(
	@IDArticol int,
	@Pret decimal(25,5)	
)
RETURNS decimal(25,5)
AS
BEGIN

	DECLARE @ResultVar decimal(25,5)
	
	SELECT @ResultVar = COALESCE(SUM(ddl.Cantitate),0) FROM DocumenteDetaliu dd 
	JOIN Documente d ON d.IDDocument=dd.IDDocument
	JOIN DocumenteDetaliuLink  ddl ON ddl.IDDocDetaliuSursa = dd.IDDocumentDetaliu
	JOIN DocumenteDetaliu ddr ON ddl.IDDocDetaliuDest = ddr.IDDocumentDetaliu
	JOIN Documente dr ON ddr.IDDocument = dr.IDDocument
	WHERE dd.IDArticol=@IDArticol AND dd.ValoareUnitara=@Pret AND 
	(d.IDTipDocument = 0 OR d.IDTipDocument = 15) AND d.AreDocGestStoc=1 AND 
	(dr.IDTipDocument in (1,13,14)) AND dr.AreDocGestStoc=1

	RETURN @ResultVar

END

GO




IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Stocuri' AND COLUMN_NAME = 'Intrari')
BEGIN
	ALTER TABLE dbo.Stocuri ADD
	Intrari  AS dbo.GetStocIntrari(IDArticol,Pret) 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Stocuri' AND COLUMN_NAME = 'Iesiri')
BEGIN
	ALTER TABLE dbo.Stocuri ADD
	Iesiri  AS dbo.GetStocIesiri(IDArticol,Pret) 
END
GO


DROP VIEW [dbo].[fares_viewDocumenteTipuriDetalii]
GO


CREATE VIEW [dbo].[fares_viewDocumenteTipuriDetalii]
AS
SELECT        dbo.Documente.IDDocument, dbo.Documente.NrDoc, dbo.Documente.DataDoc, dbo.Documente.IDPartener, dbo.Documente.CodUnitate, dbo.Documente.CotaTVA, 
                         dbo.Documente.IDTipDocument, dbo.Documente.TotalValoare, dbo.Documente.TotalValoareTVA, dbo.Documente.Total, dbo.Documente.IDRegimFiscal, 
                         dbo.Documente.UserId, dbo.Documente.IDDepartament, dbo.Documente.NrContract, dbo.Documente.DataContract, dbo.Documente.Observatii, 
                         dbo.Documente.DataScadenta, dbo.Documente.ValoareTotalaCuAdaos, dbo.Documente.NrDocReceptie, dbo.Documente.DataDocReceptie, 
                         dbo.Documente.IDGestionar, dbo.Documente.IDPredator, dbo.Documente.IDJurnal, dbo.Documente.CursValutar, dbo.Documente.CodValuta, 
                         dbo.Documente.AreDocGestStoc, dbo.Documente.DataStartProductie, dbo.Documente.Serie, dbo.Documente.Numar, dbo.Documente.IDProgramSanatate, 
                         dbo.Documente.DataCreation, dbo.Documente.TotalValoareValuta, DocumenteDetaliu.IDArticol, DocumenteDetaliu.ValoareUnitara
FROM            dbo.Documente INNER JOIN
                         dbo.TipDocument AS td ON dbo.Documente.IDTipDocument = td.IDTipDocument INNER JOIN
                             (SELECT DISTINCT IDArticol, IDDocument, ValoareUnitara
                               FROM            dbo.DocumenteDetaliu AS DocumenteDetaliu_1) AS DocumenteDetaliu ON dbo.Documente.IDDocument = DocumenteDetaliu.IDDocument

GO


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewDocumenteTipuriDetaliiIesire]'))
DROP VIEW [dbo].[fares_viewDocumenteTipuriDetaliiIesire]
GO


IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewDocumenteTipuriDetaliiIesire]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[fares_viewDocumenteTipuriDetaliiIesire]
AS
SELECT        dbo.Documente.IDDocument, dbo.Documente.NrDoc, dbo.Documente.DataDoc, dbo.Documente.IDPartener, dbo.Documente.CodUnitate, dbo.Documente.CotaTVA, 
                         dbo.Documente.IDTipDocument, dbo.Documente.TotalValoare, dbo.Documente.TotalValoareTVA, dbo.Documente.Total, dbo.Documente.IDRegimFiscal, 
                         dbo.Documente.UserId, dbo.Documente.IDDepartament, dbo.Documente.NrContract, dbo.Documente.DataContract, dbo.Documente.Observatii, 
                         dbo.Documente.DataScadenta, dbo.Documente.ValoareTotalaCuAdaos, dbo.Documente.NrDocReceptie, dbo.Documente.DataDocReceptie, 
                         dbo.Documente.IDGestionar, dbo.Documente.IDPredator, dbo.Documente.IDJurnal, dbo.Documente.CursValutar, dbo.Documente.CodValuta, 
                         dbo.Documente.AreDocGestStoc, dbo.Documente.DataStartProductie, dbo.Documente.Serie, dbo.Documente.Numar, dbo.Documente.IDProgramSanatate, 
                         dbo.Documente.DataCreation, dbo.Documente.TotalValoareValuta, dd.IDArticol, dd.ValoareUnitara
FROM            dbo.Documente INNER JOIN
                         dbo.TipDocument AS td ON dbo.Documente.IDTipDocument = td.IDTipDocument INNER JOIN
                             (SELECT DISTINCT ddr.IDArticol, ddr.IDDocument, dds.ValoareUnitara
                               FROM            dbo.DocumenteDetaliu AS dds INNER JOIN
                                                         dbo.DocumenteDetaliuLink AS ddl ON ddl.IDDocDetaliuSursa = dds.IDDocumentDetaliu INNER JOIN
                                                         dbo.DocumenteDetaliu AS ddr ON ddl.IDDocDetaliuDest = ddr.IDDocumentDetaliu) AS dd ON dbo.Documente.IDDocument = dd.IDDocument
WHERE        (td.TipOperatie LIKE ''%O%'')
' 
GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetStocIesiriData]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'
CREATE FUNCTION [dbo].[GetStocIesiriData]
(
	@IDArticol int,
	@Pret decimal(25,5),
	@LaData datetime	
)
RETURNS decimal(25,5)
AS
BEGIN
	DECLARE @ResultVar decimal(25,5)
	SELECT @ResultVar = COALESCE(SUM(ddl.Cantitate),0) FROM DocumenteDetaliu dd 
	JOIN Documente d ON d.IDDocument=dd.IDDocument
	JOIN DocumenteDetaliuLink  ddl ON ddl.IDDocDetaliuSursa = dd.IDDocumentDetaliu
	JOIN DocumenteDetaliu ddr ON ddl.IDDocDetaliuDest = ddr.IDDocumentDetaliu
	JOIN Documente dr ON ddr.IDDocument = dr.IDDocument
	WHERE dd.IDArticol=@IDArticol AND dd.ValoareUnitara=@Pret AND 
	(d.IDTipDocument = 0 OR d.IDTipDocument = 15) AND d.AreDocGestStoc=1 AND 
	(dr.IDTipDocument in (1,13,14)) AND dr.AreDocGestStoc=1 AND dr.DataDoc<=@LaData

	RETURN @ResultVar

END

' 
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetStocIntrariData]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
BEGIN
execute dbo.sp_executesql @statement = N'

CREATE FUNCTION [dbo].[GetStocIntrariData]
(
	@IDArticol int,
	@Pret decimal(25,5),
	@LaData datetime	
)

RETURNS decimal(25,5)
AS
BEGIN

	DECLARE @ResultVar decimal(25,5)

	SELECT @ResultVar = COALESCE(SUM(dd.Cantitate),0) FROM DocumenteDetaliu dd JOIN
	Documente d ON d.IDDocument=dd.IDDocument 
	WHERE dd.IDArticol=@IDArticol AND dd.ValoareUnitara = @Pret AND 
	(d.IDTipDocument = 0 OR d.IDTipDocument = 15) AND d.AreDocGestStoc=1
	AND d.DataDoc<=@LaData

	-- Return the result of the function
	RETURN @ResultVar

END

' 
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaListaStocuri]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaListaStocuri]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaListaStocuri] 
	@filtruArt varchar(8000),
	@filtruCat varchar(8000),
	@laData datetime,
	@StocuriZero bit,
	@Comparatie smallint,
	@ValoareStoc decimal(25,5),
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    SELECT *,v.Stoc*v.ValoareUnitara ValoareTotala FROM
    (SELECT art.IDArticol,st.Pret ValoareUnitara,
    art.Denumire DenumireArticol,tca.Denumire DenumireCategorie, um.Denumire DenumireUM,
    st.StocInitial StocInitial,
    st.StocPrecedent StocPrecedent,
    dbo.GetStocIntrariData(st.IDArticol,st.Pret,@laData) Intrari ,
    dbo.GetStocIesiriData(st.IDArticol,st.Pret,@laData) Iesiri,
    st.StocInitial + st.StocPrecedent+dbo.GetStocIntrariData(st.IDArticol,st.Pret,@laData)- dbo.GetStocIesiriData(st.IDArticol,st.Pret,@laData) Stoc
    FROM [Articole] art
    JOIN [TipCategoriiArticole] tca ON art.IDCategorie = tca.IDCategorie
    LEFT OUTER JOIN [Stocuri] st ON st.IDArticol = art.IDArticol 
    JOIN UnitatiMasura um ON art.IDUnitateMasura = um.IDUnitateMasura
    WHERE 
    art.CodUnitate = @CodUnitate AND
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (art.IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruCat)))=0 OR (tca.IDCategorie IN (SELECT CAST(fart.value as smallint) FROM dbo.SplitParameters(@filtruCat,',') fart))) 
	) v
    WHERE 
    (@StocuriZero=1 OR Coalesce(Stoc,0)<>0) AND
    ((@Comparatie=0 AND Coalesce(Stoc,0) >@ValoareStoc) OR (@Comparatie=1 AND Coalesce(Stoc,0) >=@ValoareStoc) OR (@Comparatie=2 AND Coalesce(Stoc,0) =@ValoareStoc)
     OR (@Comparatie=3 AND Coalesce(Stoc,0) <=@ValoareStoc) OR (@Comparatie=4 AND Coalesce(Stoc,0) <@ValoareStoc) OR (@Comparatie=5 AND Coalesce(Stoc,0) <>@ValoareStoc))
     
END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaListaFisaMagazie]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
ALTER PROCEDURE [dbo].[fares_FiltreazaListaFisaMagazie] 
	-- Add the parameters for the stored procedure here
	@filtruArt varchar(8000),
	@laData datetime,
	@CodUnitate smallint
AS
BEGIN
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    SELECT * FROM
    (SELECT  td.Denumire+''(''+td.TipOperatie + '')'' Denumire, art.IDArticol,COALESCE(docDetSursa.ValoareUnitara,docDet.ValoareUnitara) ValoareUnitara,doc.IDDocument,
    art.Denumire DenumireArticol,um.Denumire DenumireUM,
    doc.DataDoc,doc.NrDoc,
    case when td.TipOperatie=''I'' then docDet.Cantitate else 0 end Intrari,
    case when td.TipOperatie=''O'' then COALESCE(docDetL.Cantitate,0) else 0 end Iesiri,

    coalesce((select SUM(s.StocInitial+s.StocPrecedent) FROM Stocuri s where s.IDArticol=docDet.IDArticol and s.Pret = COALESCE(docDetSursa.ValoareUnitara,docDet.ValoareUnitara)),0)
    + Coalesce((
	Select SUM(Cantitate) FROM 
	DocumenteDetaliu dd 
	JOIN Documente dct on dd.IDDocument=dct.IDDocument
    join TipDocument tipd ON dct.IDTipDocument = tipd.IDTipDocument
    where dd.IDArticol = docDet.IDArticol AND dd.ValoareUnitara = COALESCE(docDetSursa.ValoareUnitara,docDet.ValoareUnitara) and dct.DataCreation<=doc.DataCreation
    and tipd.TipOperatie=''I'' and tipd.ModificaStoc=1 AND dct.AreDocGestStoc=1),
	0)
     - Coalesce((
	 Select SUM(ddl.Cantitate) FROM 
	 DocumenteDetaliu dd 
	 JOIN Documente dct on dd.IDDocument=dct.IDDocument
     join TipDocument tipd ON dct.IDTipDocument = tipd.IDTipDocument
	 join DocumenteDetaliuLink ddl ON dd.IDDocumentDetaliu = ddl.IDDocDetaliuDest
	 join DocumenteDetaliu dds ON ddl.IDDocDetaliuSursa = dds.IDDocumentDetaliu
     where dd.IDArticol = docDet.IDArticol AND dds.ValoareUnitara = COALESCE(docDetSursa.ValoareUnitara,docDet.ValoareUnitara) and dct.DataCreation<=doc.DataCreation
     and tipd.TipOperatie=''O'' and tipd.ModificaStoc=1 AND dct.AreDocGestStoc=1),0)
     stoc,
    docDet.ValoareTotala,docDet.ValoareTVA,Coalesce(doc.NrDocReceptie,'''') NrDocReceptie,doc.DataDocReceptie,
    td.IDTipDocument,coalesce(art.Lungime,0) Lungime,coalesce(art.Latime,0) Latime,Coalesce(art.Grosime,0) Grosime,Coalesce(art.Greutate,0) Greutate,
	doc.DataCreation
    FROM [Articole] art
    LEFT OUTER JOIN [DocumenteDetaliu] docDet ON docDet.IDArticol = art.IDArticol
    JOIN [Documente] doc ON doc.IDDocument = docDet.IDDocument
    JOIN [TipDocument] td ON doc.IDTipDocument = td.IDTipDocument AND td.ModificaStoc=1
    JOIN UnitatiMasura um ON art.IDUnitateMasura = um.IDUnitateMasura
	LEFT OUTER JOIN [DocumenteDetaliuLink] docDetL ON docDetL.IDDocDetaliuDest = docDet.IDDocumentDetaliu AND docDetL.Cantitate<>0
	LEFT OUTER JOIN [DocumenteDetaliu] docDetSursa ON docDetL.IDDocDetaliuSursa = docDetSursa.IDDocumentDetaliu 

    WHERE 
    art.CodUnitate = @CodUnitate AND doc.AreDocGestStoc=1 AND
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (art.IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,'','') fart)))
    )
    v
END
' 
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[exbug_GenereazaArticoleAlineate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[exbug_GenereazaArticoleAlineate]
GO

CREATE PROCEDURE [dbo].[exbug_GenereazaArticoleAlineate]
	@CodUnitate smallint
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO  [ArticoleAliniate] SELECT [ArtAl]
      ,[Denumire]
      ,[AAParinte]
      ,[Terminal]
      ,[Titlu]
      ,[Categorii]
      ,[TermDenumire]
      ,[StartDenumire]
      ,[Anexa6]
      ,@CodUnitate
  FROM [ArticoleAliniate] WHERE CodUnitate=0
END

GO



IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'FolosesteContract')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD FolosesteContract bit NOT NULL DEFAULT (0)
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportFisaPartenerului]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportFisaPartenerului]
GO


CREATE PROCEDURE [dbo].[fares_FiltreazaRaportFisaPartenerului] 
    @filtruPart varchar(8000),
    @filtruDoc varchar(8000),
	@data2 datetime,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

  SELECT * FROM [fares_FisaPartenerului] WHERE 
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruDoc)))=0 OR (IDTipDocument IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruDoc,',') fart))) AND
 	CodUnitate = @CodUnitate AND [DataDoc]<=@data2
END

GO



IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_FisaPartenerului]'))
DROP VIEW [dbo].[fares_FisaPartenerului]
GO


CREATE VIEW [dbo].[fares_FisaPartenerului]
AS
SELECT     dbo.TipDocument.Denumire +'(' + dbo.TipDocument.TipOperatie + ')'  AS TipDocument, dbo.Documente.NrDoc, dbo.Documente.DataDoc, dbo.Documente.Total AS Obligatie, 0 AS Plata, NULL AS DataExtras, 
                      dbo.Documente.IDDocument, dbo.Documente.CodUnitate, dbo.Documente.IDPartener, p.Denumire AS denPartener, dbo.TipDocument.IDTipDocument
FROM         dbo.Documente INNER JOIN
                      dbo.TipDocument ON dbo.Documente.IDTipDocument = dbo.TipDocument.IDTipDocument JOIN
                      Parteneri p ON dbo.Documente.IDPartener = p.IDPartener
UNION
SELECT     b.Denumire AS TipDocument, Numar AS NrDoc, Data AS DataDoc, 0 AS Obligatie, ValoareTotala AS Plata, a.Dataextras, NULL, a.codUnitate, a.IDPartener, 
                      p.Denumire AS denPartener, b.IDTipPlata + 1000 AS IDTipDocument
FROM         DocumentePlata a JOIN
                      TipDocumentPlata b ON a.IDTipPlata = b.IDTipPlata JOIN
                      Parteneri p ON a.IDPartener = p.IDPartener

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[balcon_GenRegistruCasa]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[balcon_GenRegistruCasa]
GO



CREATE PROCEDURE [dbo].[balcon_GenRegistruCasa]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint, 
	@DeLaData datetime,
	@PanaLaData datetime,
	@Cod varchar(50),
	@DeLaCont dbo.TipCont,
	@PanaLaCont dbo.TipCont
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
	SELECT ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc, 
	ct.DebitInitial - ct.CreditInitial + 
	(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
	WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContDebit = ct.Cont) AND rjd.DataDoc<rd.DataDoc )
	-(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
	WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContCredit = ct.Cont) AND rjd.DataDoc<rd.DataDoc ) 
		sodlzi,
	SUM(CASE WHEN ruld.ContDebit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajDebit,
	SUM(CASE WHEN ruld.ContCredit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajCredit
	FROM [Conturi] ct 
	LEFT OUTER JOIN [ConturiSpeciale] cs ON ct.Cont = cs.Cont AND ct.CodUnitate = cs.CodUnitate 
	JOIN [Rulaje] ruld ON ct.CodUnitate=ruld.CodUnitate AND (ruld.ContDebit = ct.Cont OR ruld.ContCredit=ct.Cont)
	JOIN [RulajeDoc] rd ON ruld.IDDocument = rd.IDDocument
	WHERE ct.CodUnitate = @CodUnitate AND rd.DataDoc<=@PanaLaData AND rd.DataDoc>=@DeLaData
	AND (LEN(@Cod)=0 OR cs.Tipuri LIKE @Cod)
	GROUP BY ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc,ct.Cont
		
END

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[balcon_GenRegistruCasa2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[balcon_GenRegistruCasa2]
GO


CREATE PROCEDURE [dbo].[balcon_GenRegistruCasa2]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint, 
	@DeLaData datetime,
	@PanaLaData datetime,
	@Cod varchar(50),
	@DeLaCont dbo.TipCont,
	@PanaLaCont dbo.TipCont,
	@DataDocJust bit
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF @DataDocJust=1
		SELECT ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,ruld.DataDocJust As DataDoc,
		ct.DebitInitial - ct.CreditInitial + 
		(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj 
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContDebit = ct.Cont) AND rlj.DataDocJust<ruld.DataDocJust )
		-(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj 
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContCredit = ct.Cont) AND rlj.DataDocJust<ruld.DataDocJust ) 
			sodlzi,
		SUM(CASE WHEN ruld.ContDebit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajDebit,
		SUM(CASE WHEN ruld.ContCredit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajCredit
		FROM [Conturi] ct 
		LEFT OUTER JOIN [ConturiSpeciale] cs ON ct.Cont = cs.Cont AND ct.CodUnitate = cs.CodUnitate 
		JOIN [Rulaje] ruld ON ct.CodUnitate=ruld.CodUnitate AND (ruld.ContDebit = ct.Cont OR ruld.ContCredit=ct.Cont)
		JOIN [RulajeDoc] rd ON ruld.IDDocument = rd.IDDocument
		WHERE ct.CodUnitate = @CodUnitate AND rd.DataDoc<=@PanaLaData AND rd.DataDoc>=@DeLaData
		AND (LEN(@Cod)=0 OR cs.Tipuri LIKE @Cod)
		GROUP BY ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,ruld.DataDocJust,ct.Cont
	ELSE
		SELECT ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc,
		ct.DebitInitial - ct.CreditInitial + 
		(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContDebit = ct.Cont) AND rjd.DataDoc<rd.DataDoc )
		-(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContCredit = ct.Cont) AND rjd.DataDoc<rd.DataDoc ) 
			sodlzi,
		SUM(CASE WHEN ruld.ContDebit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajDebit,
		SUM(CASE WHEN ruld.ContCredit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajCredit
		FROM [Conturi] ct 
		LEFT OUTER JOIN [ConturiSpeciale] cs ON ct.Cont = cs.Cont AND ct.CodUnitate = cs.CodUnitate 
		JOIN [Rulaje] ruld ON ct.CodUnitate=ruld.CodUnitate AND (ruld.ContDebit = ct.Cont OR ruld.ContCredit=ct.Cont)
		JOIN [RulajeDoc] rd ON ruld.IDDocument = rd.IDDocument
		WHERE ct.CodUnitate = @CodUnitate AND rd.DataDoc<=@PanaLaData AND rd.DataDoc>=@DeLaData
		AND (LEN(@Cod)=0 OR cs.Tipuri LIKE @Cod)
		GROUP BY ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc,ct.Cont
	
		
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GenNotaContabilaUnionDataDocJust]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GenNotaContabilaUnionDataDocJust]
GO

CREATE PROCEDURE [dbo].[GenNotaContabilaUnionDataDocJust]
	-- Add the parameters for the stored procedure here
	@cont TipCont,
	@CodUnitate smallint,
	@DeLaData datetime,
	@PanaLaData datetime,
	@An smallint,
	@strFilter varchar(2000),
	@strFilter2 varchar(2000),
	@strOrder varchar(1000)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @cmd varchar(5000)
	DECLARE @strCodUnitate varchar(20)
	SET @strCodUnitate = cast(@codUnitate as varchar(20))
	DECLARE @DtDataStartUI varchar(40)
	DECLARE @DtDataEndUI varchar(40)

	SET @DtDataStartUI = cast(YEAR(@DeLaData) as varchar(4)) + '-' +cast(MONTH(@DeLaData) as varchar(2)) + '-' + cast(DAY(@DeLaData) as varchar(2))
	SET @DtDataEndUI = cast(YEAR(@PanaLaData) as varchar(4)) + '-' +cast(MONTH(@PanaLaData) as varchar(2)) + '-' + cast(DAY(@PanaLaData) as varchar(2))

    -- Insert statements for procedure here
	SET @cmd = 'SELECT b.NumarDoc, b.DataDoc, b.NumarNota, a.ContDebit, a.ContCredit, 
                      b.IDJurnal, a.ValoareLei, a.DataDocJust, a.TipDocJust, a.NumarDocJust, a.ExplicatiiDocJust, 
                      b.TipFormula, c.Categorie, ''D'' AS Tip, a.CodUnitate
				FROM  [Rulaje' 
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))
				SET @cmd = @cmd + '] a INNER JOIN  [RulajeDoc'
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))                      
				SET @cmd = @cmd + '] b ON a.IDDocument = b.IDDocument INNER JOIN  [Conturi'
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))                      
				SET @cmd = @cmd + '] c ON a.ContDebit = c.Cont AND c.CodUnitate = a.CodUnitate
				WHERE [ContDebit]<>''N/A'' AND (a.CodUnitate = ' + @strCodUnitate + ') ' 
				IF @cont<> ''
					SET @cmd = @cmd + ' AND (a.ContDebit like ''' + @cont + '%'' OR a.ContCredit like ''' + @cont + '%'')'

				SET @cmd = @cmd + ' AND (a.DataDocJust >=''' +	@DtDataStartUI + ''' AND a.DataDocJust<='''	 +  @DtDataEndUI + ''')'

				IF @strFilter <> ''
					SET @cmd = @cmd + @strFilter

--				IF @strOrder = ''
--					SET @cmd = @cmd + 'ORDER BY b.DataDoc'
--				ELSE
--					SET @cmd = @cmd + @strOrder
		SET @cmd = @cmd + '  UNION SELECT b.NumarDoc, b.DataDoc, b.NumarNota, a.[ContCredit] AS [ContDebit], a.[ContDebit] AS ContCredit, 
                      b.IDJurnal, a.ValoareLei, a.DataDocJust, a.TipDocJust, a.NumarDocJust, a.ExplicatiiDocJust, 
                      b.TipFormula, c.Categorie, ''C'' AS Tip, a.CodUnitate
				FROM  [Rulaje' 
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))
				SET @cmd = @cmd + '] a INNER JOIN  [RulajeDoc'
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))                      
				SET @cmd = @cmd + '] b ON a.IDDocument = b.IDDocument INNER JOIN  [Conturi'
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))                      
				SET @cmd = @cmd + '] c ON a.ContDebit = c.Cont AND c.CodUnitate = a.CodUnitate
				WHERE [ContCredit]<>''N/A'' AND (a.CodUnitate = ' + @strCodUnitate + ') ' 
				IF @cont<> ''
					SET @cmd = @cmd + ' AND (a.ContDebit like ''' + @cont + '%'' OR a.ContCredit like ''' + @cont + '%'')'

				SET @cmd = @cmd + ' AND (a.DataDocJust >=''' +	@DtDataStartUI + ''' AND a.DataDocJust<='''	 +  @DtDataEndUI + ''')'

				IF @strFilter2 <> ''
					SET @cmd = @cmd + @strFilter2

				IF @strOrder = ''
					SET @cmd = @cmd + 'ORDER BY a.DataDocJust'
				ELSE
					SET @cmd = @cmd + @strOrder
    PRINT(@cmd)		
	EXEC(@Cmd) 
	IF @@ERROR != 0 GOTO EROARE	





	GOTO Gata
	EROARE:
		RAISERROR ('Eroare la generarea datelor pentru [NotaContabilaView]!',16,-1)
		GOTO Gata
	Gata:

END


GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[balcon_GetConturiFolosite]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[balcon_GetConturiFolosite]
GO


CREATE PROCEDURE [dbo].[balcon_GetConturiFolosite]
	@CodUnitate smallint
AS
BEGIN
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT DISTINCT co.* FROM Conturi co JOIN Rulaje rul ON (co.Cont=rul.ContDebit OR co.Cont=rul.ContCredit) AND co.CodUnitate=rul.CodUnitate
	WHERE co.CodUnitate =@CodUnitate
END

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CarteMuncaAngajator]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[CarteMuncaAngajator](
		[IDAngajator] [int] IDENTITY(1,1) NOT NULL,
		[Denumire] [varchar](250) NOT NULL,
	 CONSTRAINT [PK_CarteMuncaAngajator] PRIMARY KEY CLUSTERED 
	(
		[IDAngajator] ASC
	)
	) ON [PRIMARY]
END
GO


IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CarteMuncaIstoric]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[CarteMuncaIstoric](
		[IDCarteMunca] [int] IDENTITY(1,1) NOT NULL,
		[IDPersoana] [int] NOT NULL,
		[DeLaData] [datetime] NOT NULL,
		[PanaLaData] [datetime] NULL,
		[Prezent] bit NOT NULL DEFAULT (0),
		[IDAngajator] [int] NOT NULL,
	 CONSTRAINT [PK_CarteMuncaIstoric] PRIMARY KEY CLUSTERED 
	(
		[IDCarteMunca] ASC
	),
	CONSTRAINT [FK_CarteMuncaIstoric_CarteMuncaAngajator] FOREIGN KEY([IDAngajator]) REFERENCES [dbo].[CarteMuncaAngajator] ([IDAngajator]),
	CONSTRAINT [FK_CarteMuncaIstoric_Persoane] FOREIGN KEY([IDPersoana]) REFERENCES [dbo].[Persoane] ([IdPersoana])
	) ON [PRIMARY]

END
GO


IF NOT EXISTS (SELECT * FROM [TipContact] WHERE [IDTipContact]=5)
BEGIN
	SET IDENTITY_INSERT [TipContact] ON
	INSERT INTO [TipContact] ([IDTipContact],[Denumire])VALUES(5,'Delegat')
	SET IDENTITY_INSERT [TipContact] OFF
END
GO

IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[MijloaceTransport]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[MijloaceTransport](
	[IDMijlocTransport] [smallint] IDENTITY(1,1) NOT NULL,
	[Denumire] [varchar](150) NOT NULL,
	[NrInmatriculare] [varchar](50) NOT NULL,
	[IDPartener] [bigint] NOT NULL,
	CONSTRAINT [PK_MijloaceTransport] PRIMARY KEY CLUSTERED ([IDMijlocTransport] ASC),
	CONSTRAINT FK_MijloaceTransport_Parteneri FOREIGN KEY
	(IDPartener) REFERENCES dbo.Parteneri(IDPartener) ON UPDATE  NO ACTION ON DELETE  NO ACTION 
)
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Parteneri' AND COLUMN_NAME = 'IDContactDelegat')
BEGIN
	ALTER TABLE dbo.Parteneri ADD IDContactDelegat int NULL

	ALTER TABLE dbo.Parteneri ADD CONSTRAINT
		FK_Parteneri_Contact FOREIGN KEY(IDContactDelegat) REFERENCES dbo.Contact (IDContact) ON UPDATE  NO ACTION 
    ON DELETE  NO ACTION 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Parteneri' AND COLUMN_NAME = 'IDMijlocTransport')
BEGIN
	ALTER TABLE dbo.Parteneri ADD IDMijlocTransport smallint NULL
	ALTER TABLE dbo.Parteneri ADD CONSTRAINT
		FK_Parteneri_MijloaceTransport FOREIGN KEY
		(IDMijlocTransport) REFERENCES dbo.MijloaceTransport (IDMijlocTransport) ON UPDATE  NO ACTION 
		 ON DELETE  NO ACTION 
END	
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'IDContactDelegat')
BEGIN
	ALTER TABLE dbo.Documente ADD IDContactDelegat int NULL

	ALTER TABLE dbo.Documente ADD CONSTRAINT
		FK_Documente_Contact FOREIGN KEY(IDContactDelegat) REFERENCES dbo.Contact (IDContact) ON UPDATE  NO ACTION 
    ON DELETE  NO ACTION 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documente' AND COLUMN_NAME = 'IDMijlocTransport')
BEGIN
	ALTER TABLE dbo.Documente ADD IDMijlocTransport smallint NULL
	ALTER TABLE dbo.Documente ADD CONSTRAINT
		FK_Documente_MijloaceTransport FOREIGN KEY
		(IDMijlocTransport) REFERENCES dbo.MijloaceTransport (IDMijlocTransport) ON UPDATE  NO ACTION 
		 ON DELETE  NO ACTION 
END	
GO

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9' AND [HandlerName]='Documente_intrare_factura'
IF @Cate =0 
begin
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(31001,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Facturi',3100,1,'Documente_intrare_factura',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(31002,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Bonuri fiscale',3100,2,'Documente_intrare_bon_fiscal',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(31003,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Comenzi client',3100,3,'Documente_intrare_comanda',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(31004,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Receptii',3100,4,'Documente_intrare_receptie',NULL,NULL)


	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(32001,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Facturi',3200,1,'Documente_iesire_factura',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(32002,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Bonuri fiscale',3200,2,'Documente_iesire_bon_fiscal',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(32003,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Comenzi furnizori',3200,3,'Documente_iesire_comanda',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(32004,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Bonuri de consum',3200,4,'Documente_iesire_bon_consum',NULL,NULL)
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(32005,'892862E5-637B-4BBC-AE2B-2DAC0FFD3DF9','Avize de expeditie',3200,4,'Documente_iesire_aviz_expeditie',NULL,NULL)

	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
end 
go

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumenteDetaliu' AND COLUMN_NAME = 'TVAIncasare')
BEGIN
	ALTER TABLE dbo.DocumenteDetaliu ADD TVAIncasare bit NOT NULL DEFAULT 0
END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GenOrdonantariPlata]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GenOrdonantariPlata]
GO


CREATE PROCEDURE [dbo].[GenOrdonantariPlata]   
@idPlata int,
@idOrdonantare int OUTPUT 
AS

DECLARE @cate int

SELECT @cate = COUNT(*) FROM DocumentePlata dp WHERE dp.IDDocumentPlata=@idPlata AND dp.IDOrdonantare is not null
IF @cate<>0
BEGIN
	PRINT('Ordonontare generata')
	UPDATE [DocumentePlata] SET IDOrdonantare = null WHERE IDDocumentPlata = @idPlata
	IF @@ERROR != 0 GOTO EROARE2				
	
	DELETE FROM [Ordonantari] WHERE IDDocumentPlata = @idPlata
	IF @@ERROR != 0 GOTO EROARE2				
END

SELECT @cate = COALESCE(IDJurnal,-1) FROM DocumentePlata dp JOIN DocumentePlataDetaliu dpd ON dp.IDDocumentPlata =  dpd.IDDocumentPlata
	JOIN Documente d ON d.IDDocument = dpd.IDDocument		
	JOIN DocumenteDetaliu dd ON d.IDDocument = dd.IDDocument

IF @cate=-1
	GOTO EROARE3

SELECT @cate = COUNT(*) FROM DocumentePlata dp WHERE dp.IDDocumentPlata=@idPlata AND dp.IDOrdonantare is null

IF @cate<>0
BEGIN
PRINT('Ordonontare noua')
INSERT INTO [Ordonantari]
   ([NrDoc],[DataDoc],[IDFurnizor],[ValoareLei],[IDJurnal],[Scop],[DocJust],[AngLegal],[Achitat],[CodUnitate]
   ,[IdModPlata],[TotalDatorat],[TotalAvansuri],[ArtAl],[VizatCFP],[MotivRefuz],[IDResponsabil]
   ,[DataVizaCFP],[NrRegCFP],[IBANSursa],[IBANDest],[IDDocumentPlata])
	SELECT  (SELECT MAX(NrDoc)+1 FROM Ordonantari) AS NrDoc,
	dp.Data AS DataDoc, 
	dp.IDPartener AS IDFurnizor,
	SUM(dd.ValoareTotala +dd.ValoareTVA) As ValoareLei,
	d.IDJurnal AS IDJurnal,
	'PLATA ' + MAX(dp.Numar) + '/' +CAST(DAY(MAX(dp.Data)) AS Varchar(2)) +'.' + CAST(MONTH(MAX(dp.Data)) AS Varchar(2)) + '.' + CAST(YEAR(MAX(dp.Data)) AS Varchar(4)) AS Scop,
	'FACT ' + MAX(d.NrDoc) + '/' +CAST(DAY(MAX(d.DataDoc)) AS Varchar(2)) +'.' + CAST(MONTH(MAX(d.DataDoc)) AS Varchar(2)) + '.' + CAST(YEAR(MAX(d.DataDoc)) AS Varchar(4))  AS [DocJust],
	'ANG LEGAL'	AS [AngLegal],
	0 AS Achitat,
	MAX(d.CodUnitate) AS [CodUnitate],
	(SELECT MIN(IDModPlata) FROM ModPlata) AS [IdModPlata],
	SUM(dd.ValoareTotala + dd.ValoareTVA) As [TotalDatorat],
	0 AS [TotalAvansuri],
	dd.ArtAl aS [ArtAl],
	1 AS [VizatCFP],
	'' AS [MotivRefuz],
	(SELECT MAX(IDResponsabil) FROM Ordonantari) AS [IDResponsabil],
	dp.Data AS [DataVizaCFP],
	(SELECT MAX(NrRegCFP) FROM Ordonantari) AS NrRegCFP,
	MAX(j.IBAN) AS [IBANSursa],
	MAX(f.ContBancar) AS [IBANDest],
	@idPlata AS	[IDDocumentPlata]
	FROM DocumentePlata dp JOIN DocumentePlataDetaliu dpd ON dp.IDDocumentPlata =  dpd.IDDocumentPlata
	JOIN Documente d ON d.IDDocument = dpd.IDDocument		
	JOIN DocumenteDetaliu dd ON d.IDDocument = dd.IDDocument
	JOIN Jurnale j ON j.CodUnitate = d.CodUnitate AND d.IDJurnal = j.IDJurnal
	JOIN Parteneri f ON f.CodUnitate = d.CodUnitate AND d.IDPartener = f.IDPartener
	WHERE dp.IDDocumentPlata = @idPlata  AND dp.IDOrdonantare is Null
	GROUP BY dp.IDPartener,d.IDJurnal,dd.ArtAl,dp.Data
	IF @@ERROR != 0 GOTO EROARE				
	PRINT('Ordonontare noua generata')
	UPDATE [DocumentePlata] SET IdOrdonantare= @@IDENTITY WHERE IDDocumentPlata = @idPlata  AND IDOrdonantare is null
	IF @@ERROR != 0 GOTO EROARE1				
	PRINT('Legatura plata ordonantare - generata')
	SET @idOrdonantare = @@IDENTITY
END




GOTO Gata
EROARE:
	RAISERROR ('Eroare la generarea ordonantarii',16,-1)
	GOTO Gata
EROARE1:
	RAISERROR ('Nu se poate seta ordonantarea pentru plata',16,-1)
	GOTO Gata
EROARE2:
	RAISERROR ('Nu pot sterge ordonantarile generate',16,-1)
	GOTO Gata
EROARE3:
	RAISERROR ('Factura nu are trecut capitolul!',16,-1)
	GOTO Gata


Gata:

GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumentePlataDetaliu' AND COLUMN_NAME = 'ValoareTVA')
BEGIN
	ALTER TABLE dbo.DocumentePlataDetaliu ADD ValoareTVA decimal(18,2) NOT NULL DEFAULT 0
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Parteneri' AND COLUMN_NAME = 'ScadentaFacturiClient')
BEGIN
	ALTER TABLE dbo.Parteneri ADD ScadentaFacturiClient int NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Parteneri' AND COLUMN_NAME = 'ScadentaFacturiFurnizor')
BEGIN
	ALTER TABLE dbo.Parteneri ADD ScadentaFacturiFurnizor int NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Parteneri' AND COLUMN_NAME = 'ScadentaFacturiSfarsitLuna')
BEGIN
	ALTER TABLE dbo.Parteneri ADD ScadentaFacturiSfarsitLuna bit NOT NULL DEFAULT 0
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'ZileScadentaClient')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD ZileScadentaClient int NOT NULL DEFAULT 15
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'ZileScadentaFurnizor')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD ZileScadentaFurnizor int NOT NULL DEFAULT 15
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'TVAIncasareImplicit')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD TVAIncasareImplicit bit NOT NULL DEFAULT 1
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'PermiteTVALaIncasare')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD PermiteTVALaIncasare bit NOT NULL DEFAULT 1
END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewArticoleComanda]'))
DROP VIEW [dbo].[fares_viewArticoleComanda]
GO


CREATE VIEW [dbo].[fares_viewArticoleComanda]
AS
SELECT     dbo.Articole.Denumire, dbo.ArticoleParteneri.CodArticol, dbo.Articole.CodArticol AS MyCodArticol, dbo.Documente.IDDocument, dbo.Articole.CodCPV, 
                      dbo.UnitatiMasura.Denumire AS UM, dbo.DocumenteDetaliu.Cantitate, dbo.DocumenteDetaliu.ValoareUnitara, dbo.DocumenteDetaliu.IDArticol, 
                      dbo.DocumenteDetaliu.Cantitate * dbo.DocumenteDetaliu.ValoareUnitara AS ValoareTotala, dbo.DocumenteDetaliu.TermenLivrare, 
                      dbo.DocumenteDetaliu.IDDocumentDetaliu, dbo.ArticoleVariante.Denumire AS Varianta, dbo.DocumenteDetaliu.Observatii, dbo.DocumenteDetaliu.ValoareTVA, 
                      dbo.DocumenteDetaliu.ValoareUnitaraValuta, dbo.DocumenteDetaliu.TVAIncasare
FROM         dbo.DocumenteDetaliu INNER JOIN
                      dbo.Articole ON dbo.DocumenteDetaliu.IDArticol = dbo.Articole.IDArticol INNER JOIN
                      dbo.UnitatiMasura ON dbo.DocumenteDetaliu.IDUnitateMasura = dbo.UnitatiMasura.IDUnitateMasura INNER JOIN
                      dbo.Documente ON dbo.DocumenteDetaliu.IDDocument = dbo.Documente.IDDocument LEFT OUTER JOIN
                      dbo.ArticoleVariante ON dbo.DocumenteDetaliu.IDVariantaArticol = dbo.ArticoleVariante.IDVariantaArticol AND 
                      dbo.Articole.IDArticol = dbo.ArticoleVariante.IDArticol LEFT OUTER JOIN
                      dbo.ArticoleParteneri ON dbo.DocumenteDetaliu.IDArticol = dbo.ArticoleParteneri.IDArticol AND dbo.Documente.IDPartener = dbo.ArticoleParteneri.IDPartener

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_GenereazaJurnalCumparari]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_GenereazaJurnalCumparari]
GO


CREATE PROCEDURE [dbo].[fares_GenereazaJurnalCumparari] 
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint, 
	@DeLaData datetime,
	@PanaLaData datetime
AS

BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT NrDoc,DataDoc,doc.CodUnitate,part.CUI,part.Denumire,part.AtributFiscal,
docd.*
FROM 
Documente doc JOIN Parteneri part ON doc.IDPartener = part.IDPartener
JOIN TipDocument tipd ON doc.IDTipDocument = tipd.IDTipDocument
JOIN 

	(SELECT dd.IDDocument,SUM(CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END+ValoareTVA) ValoareTotalaSiTVA,
	SUM(CASE WHEN dd.IDRegimFiscal IN (4,17,18,19,27) AND (dd.CotaTVA=24 OR dd.CotaTVA=19)  THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) Baza24,
	SUM(CASE WHEN dd.IDRegimFiscal IN (4,17,18,19,27) AND (dd.CotaTVA=24 OR dd.CotaTVA=19) THEN ValoareTVA ELSE 0 END) TVA24,
	SUM(CASE WHEN dd.IDRegimFiscal IN (4,17,18,19,27) AND dd.CotaTVA=9 THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) Baza9,
	SUM(CASE WHEN dd.IDRegimFiscal IN (4,17,18,19,27) AND dd.CotaTVA=9 THEN ValoareTVA ELSE 0 END) TVA9,
	SUM(CASE WHEN dd.IDRegimFiscal IN (6) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) InversBaza,
	SUM(CASE WHEN dd.IDRegimFiscal IN (6) THEN ValoareTVA ELSE 0 END) InversTVA,
	SUM(CASE WHEN dd.IDRegimFiscal IN (20) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END+ValoareTVA ELSE 0 END) ImportTaraScutite,
	SUM(CASE WHEN dd.IDRegimFiscal IN (27) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) ObligatBaza,
	SUM(CASE WHEN dd.IDRegimFiscal IN (27) THEN ValoareTVA ELSE 0 END) ObligatTVA,
	SUM(CASE WHEN dd.IDRegimFiscal IN (29) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) BCScutit,
	SUM(CASE WHEN dd.IDRegimFiscal IN (22) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) DRScutit,
	SUM(CASE WHEN dd.IDRegimFiscal IN (24) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) NFScutit,
	SUM(CASE WHEN dd.IDRegimFiscal IN (30) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) BCNeimp,
	SUM(CASE WHEN dd.IDRegimFiscal IN (23) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) DRNeimp,
	SUM(CASE WHEN dd.IDRegimFiscal IN (26) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) NFNeimp,
	SUM(CASE WHEN dd.IDRegimFiscal IN (28) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) BCBI,
	SUM(CASE WHEN dd.IDRegimFiscal IN (21) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) DRBI,
	SUM(CASE WHEN dd.IDRegimFiscal IN (24) THEN CASE WHEN IDTipDocument=10 THEN ValoareTotala-ValoareTVA  ELSE ValoareTotala END ELSE 0 END) NFBI,
	SUM(CASE WHEN dd.IDRegimFiscal IN (28) THEN ValoareTVA ELSE 0 END) BCTVA,
	SUM(CASE WHEN dd.IDRegimFiscal IN (21) THEN ValoareTVA ELSE 0 END) DRTVA,
	SUM(CASE WHEN dd.IDRegimFiscal IN (24) THEN ValoareTVA ELSE 0 END) NFTVA

	FROM DocumenteDetaliu dd JOIN Documente d ON dd.IDDocument=d.IDDocument
	GROUP BY dd.IDDocument) docd ON doc.IDDocument = docd.IDDocument
	
	
	WHERE tipd.IDTipDocument in (0,10) AND doc.CodUnitate=@CodUnitate AND 
	doc.DataDoc>=@DeLaData AND doc.DataDoc<=@PanaLaData AND LTRIM(RTRIM(part.AtributFiscal))<>''
	ORDER BY DataDoc
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumentePlata' AND COLUMN_NAME = 'ValoareTotalaTVA')
BEGIN
	ALTER TABLE [DocumentePlata] ADD ValoareTotalaTVA decimal(18,2) NOT NULL DEFAULT (0)
END
GO



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PontajAutomat]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[PontajAutomat](
	[IDPontajAutomat] [bigint] IDENTITY(1,1) NOT NULL,
	[Data] [datetime] NOT NULL,
	[IDCard] [varchar](30) NOT NULL,
	[CreationDate] [datetime] NOT NULL DEFAULT GETDATE(),
CONSTRAINT [PK_PontajAutomat] PRIMARY KEY CLUSTERED ([IDPontajAutomat] ASC)
) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'GestiuneCantitativa')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD GestiuneCantitativa bit NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'PermitePretZero')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD PermitePretZero bit NOT NULL DEFAULT 0
END
GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Stocuri' AND COLUMN_NAME = 'Iesiri')
BEGIN
	ALTER TABLE dbo.Stocuri DROP COLUMN Iesiri
END
GO

DROP FUNCTION [dbo].[GetStocIesiri]
GO

CREATE FUNCTION [dbo].[GetStocIesiri]
(
	@CodUnitate smallint,
	@IDArticol int,
	@Pret decimal(25,5)	
)
RETURNS decimal(25,5)
AS
BEGIN

	DECLARE @ResultVar decimal(25,5)
	DECLARE @StocCantitativ bit
	SET @StocCantitativ = 0
	SET @ResultVar = 0
	
	SELECT @StocCantitativ = GestiuneCantitativa  FROM FaresSetup WHERE CodUnitate = @CodUnitate

	IF @StocCantitativ=0 
	BEGIN
		SELECT @ResultVar = COALESCE(SUM(ddl.Cantitate),0) FROM DocumenteDetaliu dd 
		JOIN Documente d ON d.IDDocument=dd.IDDocument
		JOIN DocumenteDetaliuLink  ddl ON ddl.IDDocDetaliuSursa = dd.IDDocumentDetaliu
		JOIN DocumenteDetaliu ddr ON ddl.IDDocDetaliuDest = ddr.IDDocumentDetaliu
		JOIN Documente dr ON ddr.IDDocument = dr.IDDocument
		WHERE dd.IDArticol=@IDArticol AND dd.ValoareUnitara=@Pret AND 
		(d.IDTipDocument = 0 OR d.IDTipDocument = 15) AND d.AreDocGestStoc=1 AND 
		(dr.IDTipDocument in (1,13,14)) AND dr.AreDocGestStoc=1
	END
	ELSE
	BEGIN
		SELECT @ResultVar = COALESCE(SUM(dd.Cantitate),0) FROM DocumenteDetaliu dd 
		JOIN Documente d ON d.IDDocument=dd.IDDocument
		WHERE dd.IDArticol=@IDArticol  AND 
		(d.IDTipDocument in (1,13,14)) AND d.AreDocGestStoc=1	
	END
	
	RETURN @ResultVar

END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Stocuri' AND COLUMN_NAME = 'Iesiri')
BEGIN
	ALTER TABLE dbo.Stocuri ADD
	Iesiri  AS dbo.GetStocIesiri(CodUnitate,IDArticol,Pret) 
END
GO


IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[Stoc_DocumenteDetaliu_Insert]'))
DROP TRIGGER [dbo].[Stoc_DocumenteDetaliu_Insert]
GO


CREATE TRIGGER [dbo].[Stoc_DocumenteDetaliu_Insert]
   ON  [dbo].[DocumenteDetaliu]
   AFTER INSERT,UPDATE,DELETE
AS 
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @GestiuneCantitativa bit
	SET @GestiuneCantitativa = 0
	SELECT @GestiuneCantitativa = GestiuneCantitativa FROM FaresSetup fs JOIN inserted i ON i.CodUnitate = fs.CodUnitate
	
	
	--SE ADAUGA POZITIA IN STOCURI FARA VALORI
	IF @GestiuneCantitativa = 0
	BEGIN
		INSERT INTO Stocuri 
		([IDArticol],[CodUnitate],[Pret],[StocInitial],[StocPrecedent],[IDDepartament],[IDVarinataArticol],PretCodValuta,PretValuta)
		SELECT i.IDArticol, d.CodUnitate, i.ValoareUnitara,0,0,null,i.IDVariantaArticol,d.CodValuta,i.ValoareUnitaraValuta
		FROM inserted i JOIN  Documente d ON i.IDDocument = d.IDDocument JOIN TipDocument td ON td.IDTipDocument = d.IDTipDocument
		WHERE
		td.ModificaStoc=1 AND td.TipOperatie like '%I%' AND
		Not exists(SELECT * FROM Stocuri  s where s.IDArticol=i.IDArticol AND s.CodUnitate = d.CodUnitate AND s.Pret=i.ValoareUnitara and 
		((s.IDVarinataArticol = i.IDVariantaArticol) or ((s.IDVarinataArticol is null) and (i.IDVariantaArticol is null))))
	END
	ELSE
	BEGIN
		INSERT INTO Stocuri 
		([IDArticol],[CodUnitate],[Pret],[StocInitial],[StocPrecedent],[IDDepartament],[IDVarinataArticol],PretCodValuta,PretValuta)
		SELECT i.IDArticol, d.CodUnitate,0,0,0,null,i.IDVariantaArticol,d.CodValuta,i.ValoareUnitaraValuta
		FROM inserted i JOIN  Documente d ON i.IDDocument = d.IDDocument JOIN TipDocument td ON td.IDTipDocument = d.IDTipDocument
		WHERE
		td.ModificaStoc=1 AND td.TipOperatie like '%I%' AND
		Not exists(SELECT * FROM Stocuri  s where s.IDArticol=i.IDArticol AND s.CodUnitate = d.CodUnitate AND s.Pret=0 and 
		((s.IDVarinataArticol = i.IDVariantaArticol) or ((s.IDVarinataArticol is null) and (i.IDVariantaArticol is null))))
	END
	
END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewDocumenteTipuriDetalii]'))
DROP VIEW [dbo].[fares_viewDocumenteTipuriDetalii]
GO


CREATE VIEW [dbo].[fares_viewDocumenteTipuriDetalii]
AS
SELECT     dbo.Documente.IDDocument, dbo.Documente.NrDoc, dbo.Documente.DataDoc, dbo.Documente.IDPartener, dbo.Documente.CodUnitate, dbo.Documente.CotaTVA, dbo.Documente.IDTipDocument, 
                      dbo.Documente.TotalValoare, dbo.Documente.TotalValoareTVA, dbo.Documente.Total, dbo.Documente.IDRegimFiscal, dbo.Documente.UserId, dbo.Documente.IDDepartament, 
                      dbo.Documente.NrContract, dbo.Documente.DataContract, dbo.Documente.Observatii, dbo.Documente.DataScadenta, dbo.Documente.ValoareTotalaCuAdaos, dbo.Documente.NrDocReceptie, 
                      dbo.Documente.DataDocReceptie, dbo.Documente.IDGestionar, dbo.Documente.IDPredator, dbo.Documente.IDJurnal, dbo.Documente.CursValutar, dbo.Documente.CodValuta, 
                      dbo.Documente.AreDocGestStoc, dbo.Documente.DataStartProductie, dbo.Documente.Serie, dbo.Documente.Numar, dbo.Documente.IDProgramSanatate, dbo.Documente.DataCreation, 
                      dbo.Documente.TotalValoareValuta, DocumenteDetaliu.IDArticol, DocumenteDetaliu.ValoareUnitara, dbo.Documente.IDContactDelegat, dbo.Documente.IDMijlocTransport
FROM         dbo.Documente INNER JOIN
                      dbo.TipDocument AS td ON dbo.Documente.IDTipDocument = td.IDTipDocument INNER JOIN
                          (SELECT DISTINCT IDArticol, IDDocument, ValoareUnitara
                            FROM          dbo.DocumenteDetaliu AS DocumenteDetaliu_1) AS DocumenteDetaliu ON dbo.Documente.IDDocument = DocumenteDetaliu.IDDocument

GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewDocumenteTipuriDetaliiIesire]'))
DROP VIEW [dbo].[fares_viewDocumenteTipuriDetaliiIesire]
GO

CREATE VIEW [dbo].[fares_viewDocumenteTipuriDetaliiIesire]
AS
SELECT     dbo.Documente.IDDocument, dbo.Documente.NrDoc, dbo.Documente.DataDoc, dbo.Documente.IDPartener, dbo.Documente.CodUnitate, dbo.Documente.CotaTVA, dbo.Documente.IDTipDocument, 
                      dbo.Documente.TotalValoare, dbo.Documente.TotalValoareTVA, dbo.Documente.Total, dbo.Documente.IDRegimFiscal, dbo.Documente.UserId, dbo.Documente.IDDepartament, 
                      dbo.Documente.NrContract, dbo.Documente.DataContract, dbo.Documente.Observatii, dbo.Documente.DataScadenta, dbo.Documente.ValoareTotalaCuAdaos, dbo.Documente.NrDocReceptie, 
                      dbo.Documente.DataDocReceptie, dbo.Documente.IDGestionar, dbo.Documente.IDPredator, dbo.Documente.IDJurnal, dbo.Documente.CursValutar, dbo.Documente.CodValuta, 
                      dbo.Documente.AreDocGestStoc, dbo.Documente.DataStartProductie, dbo.Documente.Serie, dbo.Documente.Numar, dbo.Documente.IDProgramSanatate, dbo.Documente.DataCreation, 
                      dbo.Documente.TotalValoareValuta, dd.IDArticol, dd.ValoareUnitara, dbo.Documente.IDContactDelegat, dbo.Documente.IDMijlocTransport
FROM         dbo.Documente INNER JOIN
                      dbo.TipDocument AS td ON dbo.Documente.IDTipDocument = td.IDTipDocument INNER JOIN
                          (SELECT DISTINCT ddr.IDArticol, ddr.IDDocument, dds.ValoareUnitara
                            FROM          dbo.DocumenteDetaliu AS dds INNER JOIN
                                                   dbo.DocumenteDetaliuLink AS ddl ON ddl.IDDocDetaliuSursa = dds.IDDocumentDetaliu INNER JOIN
                                                   dbo.DocumenteDetaliu AS ddr ON ddl.IDDocDetaliuDest = ddr.IDDocumentDetaliu) AS dd ON dbo.Documente.IDDocument = dd.IDDocument
WHERE     (td.TipOperatie LIKE '%O%')
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GenOrdonantariPlata]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GenOrdonantariPlata]
GO

IF NOT EXISTS (SELECT * FROM [regimFiscal] WHERE [IDRegimFiscal]>50)
BEGIN
	SET IDENTITY_INSERT [regimFiscal] ON
	DELETE FROM [regimFiscal] WHERE IDRegimFiscal=31
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(51,'I',1,'Importuri de bunuri',1,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(52,'I',1,'Achizitii de bunuri din tara si din import scutite sau neimpozabile',0,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(53,'I',1,'Achizitii intracomunitare de bunuri',1,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(54,'I',1,'Achizitii intracomunitare de servicii',1,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(55,'I',1,'Achizitii intracomunitare de bunuri si servicii scutite',0,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(56,'I',1,'Achizitii intracomunitare de bunuri si servicii neimpozabile',0,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(57,'I',1,'Achizitii pt. care ben. este obligat la plata TVA (altele decat achiz. IC de bun. si serv.)',1,1)

	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(61,'O',1,'Operatiuni supuse regimurilor speciale de TVA',0,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(62,'O',1,'Prestari intracomunitare de servicii cu drept de deducere',0,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(63,'O',1,'Prestari intracomunitare de servicii fara drept de deducere',0,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(64,'O',1,'Livrari/Prestari intracomunitare de bunuri scutite conform art.143 alin.(2) lit.a) si d) din CF',0,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(65,'O',1,'Livrari/Prestari intracomunitare de bunuri scutite conform art.143 alin.(2) lit.b) si c) din CF',0,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(66,'O',1,'Exporturi si alte livrari de bunuri si prestari de servicii scutite cu drept de deducere',0,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(67,'O',1,'Livrari/Prestari scutite fara drept de deducere',0,1)
	INSERT INTO [regimFiscal] ([IDRegimFiscal],[TipOperatie],[Vizibil],[Denumire],[CuTVA],[IntraIn394])VALUES(68,'O',1,'Operatiuni neimpozabile in Romania (altele decat prestarile IC de servicii)',0,1)
	SET IDENTITY_INSERT [regimFiscal] OFF
END
GO



CREATE PROCEDURE [dbo].[GenOrdonantariPlata]   
@idPlata int,
@idOrdonantare int OUTPUT 
AS
DECLARE @cate int

SELECT @cate = COALESCE(IDJurnal,-1) FROM DocumentePlata dp JOIN DocumentePlataDetaliu dpd ON dp.IDDocumentPlata =  dpd.IDDocumentPlata
	JOIN Documente d ON d.IDDocument = dpd.IDDocument		
	JOIN DocumenteDetaliu dd ON d.IDDocument = dd.IDDocument
	WHERE dp.IDDocumentPlata = @idPlata 

IF @cate=-1
	GOTO EROARE3
	
DECLARE @cate2 varchar(200)

SELECT @cate2 = COALESCE(MAX(dd.ArtAl),'') FROM DocumentePlata dp JOIN DocumentePlataDetaliu dpd ON dp.IDDocumentPlata =  dpd.IDDocumentPlata
	JOIN Documente d ON d.IDDocument = dpd.IDDocument		
	JOIN DocumenteDetaliu dd ON d.IDDocument = dd.IDDocument
	WHERE dp.IDDocumentPlata = @idPlata 

IF @cate2=''
	GOTO EROARE4

DECLARE @idResponsabilImplicit int
SELECT @idResponsabilImplicit = IDResponsabil  FROM ResponsabilVizaCFP


IF @idResponsabilImplicit IS NULL
	GOTO EROARE5



SELECT @cate = COUNT(*) FROM [Ordonantari] ord WHERE ord.IDDocumentPlata = @idPlata
--sterge ordonantarile care au fost generate
IF @cate<>0
BEGIN
	PRINT('Sterge ordonantarile existente')	
	DELETE FROM [Ordonantari] WHERE IDDocumentPlata = @idPlata
	IF @@ERROR != 0 GOTO EROARE2				
END


PRINT('Ordonontare noua')
INSERT INTO [Ordonantari]
   ([NrDoc],[DataDoc],[IDFurnizor],[ValoareLei],[IDJurnal],[Scop],[DocJust],[AngLegal],[Achitat],[CodUnitate]
   ,[IdModPlata],[TotalDatorat],[TotalAvansuri],[ArtAl],[VizatCFP],[MotivRefuz],[IDResponsabil]
   ,[DataVizaCFP],[NrRegCFP],[IBANSursa],[IBANDest],[IDDocumentPlata])
	SELECT  (SELECT COALESCE(MAX(NrDoc),0)+1 FROM Ordonantari) AS NrDoc,
	dp.Data AS DataDoc, 
	dp.IDPartener AS IDFurnizor,
	SUM(dd.ValoareTotala +dd.ValoareTVA) As ValoareLei,
	d.IDJurnal AS IDJurnal,
	'PLATA ' + MAX(dp.Numar) + '/' +CAST(DAY(MAX(dp.Data)) AS Varchar(2)) +'.' + CAST(MONTH(MAX(dp.Data)) AS Varchar(2)) + '.' + CAST(YEAR(MAX(dp.Data)) AS Varchar(4)) AS Scop,
	'FACT ' + MAX(d.NrDoc) + '/' +CAST(DAY(MAX(d.DataDoc)) AS Varchar(2)) +'.' + CAST(MONTH(MAX(d.DataDoc)) AS Varchar(2)) + '.' + CAST(YEAR(MAX(d.DataDoc)) AS Varchar(4))  AS [DocJust],
	'ANG LEGAL'	AS [AngLegal],
	0 AS Achitat,
	MAX(d.CodUnitate) AS [CodUnitate],
	(SELECT MIN(IDModPlata) FROM ModPlata) AS [IdModPlata],
	SUM(dd.ValoareTotala + dd.ValoareTVA) As [TotalDatorat],
	0 AS [TotalAvansuri],
	MAX(dd.ArtAl) aS [ArtAl],
	1 AS [VizatCFP],
	'' AS [MotivRefuz],
	(SELECT COALESCE(MAX(IDResponsabil),@idResponsabilImplicit) FROM Ordonantari)  AS [IDResponsabil],
	dp.Data AS [DataVizaCFP],
	(SELECT COALESCE(MAX(NrRegCFP),0)+1 FROM Ordonantari) AS NrRegCFP,
	MAX(j.IBAN) AS [IBANSursa],
	MAX(f.ContBancar) AS [IBANDest],
	@idPlata AS	[IDDocumentPlata]
	FROM DocumentePlata dp JOIN DocumentePlataDetaliu dpd ON dp.IDDocumentPlata =  dpd.IDDocumentPlata
	JOIN Documente d ON d.IDDocument = dpd.IDDocument		
	JOIN DocumenteDetaliu dd ON d.IDDocument = dd.IDDocument
	JOIN Jurnale j ON j.CodUnitate = d.CodUnitate AND d.IDJurnal = j.IDJurnal
	JOIN Parteneri f ON d.IDPartener = f.IDPartener
	WHERE dp.IDDocumentPlata = @idPlata 
	GROUP BY dp.IDPartener,d.IDJurnal,dd.ArtAl,dp.Data
	IF @@ERROR != 0 GOTO EROARE		
	SET @idOrdonantare = @@IDENTITY	
	





GOTO Gata
EROARE:
	RAISERROR ('Eroare la generarea ordonantarii',16,-1)
	GOTO Gata
EROARE1:
	RAISERROR ('Nu se poate seta ordonantarea pentru plata',16,-1)
	GOTO Gata
EROARE2:
	RAISERROR ('Nu pot sterge ordonantarile generate',16,-1)
	GOTO Gata
EROARE3:
	RAISERROR ('Factura nu are trecut capitolul!',16,-1)
	GOTO Gata
EROARE4:
	RAISERROR ('Factura nu are specificate articolule sau aliniatele pe detaliere!',16,-1)
	GOTO Gata
EROARE5:
	RAISERROR ('Nu a fost definit nici un responsabil pentru viza CFP!',16,-1)
	GOTO Gata



Gata:



GO


IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'DocumentePlata' AND COLUMN_NAME = 'IDOrdonantare')
BEGIN 
	ALTER TABLE dbo.DocumentePlata  DROP CONSTRAINT FK_DocumentePlata_Ordonantare
	ALTER TABLE dbo.DocumentePlata  DROP COLUMN IDOrdonantare
END
go

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_ParteneriCUI]'))
DROP VIEW [dbo].[fares_ParteneriCUI]
GO


CREATE VIEW [dbo].[fares_ParteneriCUI]
AS
SELECT     IDPartener, CodUnitate, CUI, Denumire + ' (' + LTRIM(RTRIM(CAST(CUI AS VARCHAR(20)))) + ')' AS Denumire, ConditiiDePlata, ContClient, Cont
FROM         dbo.Parteneri

GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[ExBugViewPersoane]'))
DROP VIEW [dbo].[ExBugViewPersoane]
GO



CREATE VIEW [dbo].[ExBugViewPersoane]
AS
SELECT     IdPersoana, NumePrenume, CodUnitate
FROM         dbo.Persoane

GO





IF  EXISTS (SELECT * FROM sysobjects WHERE id =  OBJECT_ID(N'[dbo].[fares_FiltreazaDocumente]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaDocumente]
GO


CREATE PROCEDURE [dbo].[fares_FiltreazaDocumente] 
	-- Add the parameters for the stored procedure here
	@filtru varchar(500),
	@an varchar(4)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	DECLARE @sel varchar(2000)
	SET @sel = 'SELECT * FROM [Documente'+@an+'] where IDDocument in 
		(select [Documente'+@an+'].IDDocument FROM [Documente'+@an+']  JOIN [DocumenteDetaliu'+@an+']  ON [Documente'+@an+'].IDDocument = [DocumenteDetaliu'+@an+'].IDDocument WHERE ' +@filtru  + ')'
	EXEC(@sel)
END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[balcon_GenRegistruCasa]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[balcon_GenRegistruCasa]
GO


CREATE PROCEDURE [dbo].[balcon_GenRegistruCasa]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint, 
	@DeLaData datetime,
	@PanaLaData datetime,
	@Cod varchar(50),
	@DeLaCont dbo.TipCont,
	@PanaLaCont dbo.TipCont
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF LEN(@Cod)=0
		SELECT ct.Cont,ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc, 
		ct.DebitInitial - ct.CreditInitial + 
		(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContDebit = ct.Cont) AND rjd.DataDoc<rd.DataDoc )
		-(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContCredit = ct.Cont) AND rjd.DataDoc<rd.DataDoc ) 
		 sodlzi,
		SUM(CASE WHEN ruld.ContDebit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajDebit,
		SUM(CASE WHEN ruld.ContCredit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajCredit
		FROM [Conturi] ct 
		JOIN [Rulaje] ruld ON ct.CodUnitate=ruld.CodUnitate AND (ruld.ContDebit = ct.Cont OR ruld.ContCredit=ct.Cont)
		JOIN [RulajeDoc] rd ON ruld.IDDocument = rd.IDDocument
		WHERE ct.CodUnitate = @CodUnitate AND rd.DataDoc<=@PanaLaData AND 
		rd.DataDoc>=@DeLaData AND 
		(LEN(@DeLaCont)=0 OR ct.Cont >= @DeLaCont) AND (LEN(@PanaLaCont) = 0 OR ct.Cont<=@PanaLaCont)
		GROUP BY ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc,ct.Cont
		ORDER BY ct.Cont,rd.DataDoc
	ELSE
		SELECT ct.Cont,ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc, 
		ct.DebitInitial - ct.CreditInitial + 
		(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContDebit = ct.Cont) AND rjd.DataDoc<rd.DataDoc )
		-(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContCredit = ct.Cont) AND rjd.DataDoc<rd.DataDoc ) 
		 sodlzi,
		SUM(CASE WHEN ruld.ContDebit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajDebit,
		SUM(CASE WHEN ruld.ContCredit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajCredit
		FROM [Conturi] ct 
		JOIN [ConturiSpeciale] cs ON ct.Cont = cs.Cont AND ct.CodUnitate = cs.CodUnitate AND cs.Tipuri LIKE @Cod
		JOIN [Rulaje] ruld ON ct.CodUnitate=ruld.CodUnitate AND (ruld.ContDebit = ct.Cont OR ruld.ContCredit=ct.Cont)
		JOIN [RulajeDoc] rd ON ruld.IDDocument = rd.IDDocument
		WHERE ct.CodUnitate = @CodUnitate AND rd.DataDoc<=@PanaLaData AND rd.DataDoc>=@DeLaData
		GROUP BY ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc,ct.Cont
		ORDER BY ct.Cont,rd.DataDoc
END

GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[exbug_RegistrulProiectelor]'))
DROP VIEW [dbo].[exbug_RegistrulProiectelor]
GO

CREATE VIEW [dbo].[exbug_RegistrulProiectelor]
AS
SELECT     'Ordonantare de plata' AS Den_Doc, o.NrDoc, o.DataDoc, o.Scop, p.NumePrenume, o.ValoareLei, o.DataVizaCFP, o.Achitat, o.MotivRefuz, o.VizatCFP, 
                      d.Nume AS departament, o.DocJust, o.CodUnitate
FROM         dbo.Ordonantari AS o LEFT OUTER JOIN
                      dbo.PersoaneVizaCFP AS p ON o.IDResponsabil = p.IDResponsabil LEFT OUTER JOIN
                      dbo.AngajatiSalarizare AS a ON a.IdPersoana = p.IDPersoana LEFT OUTER JOIN
                      dbo.Departamente AS d ON a.IDDepartament = d.IDDepartament

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CreazaArhiva]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CreazaArhiva]
GO

CREATE PROCEDURE [dbo].[CreazaArhiva]
	@An smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @strContAn varchar(40)
	DECLARE @Comanda varchar(3000)
	DECLARE @existTableCont bit
	
	SET @strContAn = 'Conturi' + cast(@An AS varchar(4)) 
	SET @existTableCont = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strContAn)
		SET @existTableCont = 1
	
	--verifica existenta tabeleli arhiva
	SET @Comanda = 'CREATE TABLE [' + @strContAn + '] (
		[Cont] [dbo].[TipCont] NOT NULL,
		[CodUnitate] [smallint] NOT NULL,
		[Denumire] [varchar](200) NOT NULL,
		[Tip] [char](1) NOT NULL,
		[Terminal] [bit] NOT NULL,
		[ContParinte] [dbo].[TipCont] NOT NULL,
		[EsteAnalitic] [bit] NOT NULL,
		[DebitInitial] [decimal](20, 2) NOT NULL,
		[CreditInitial] [decimal](20, 2) NOT NULL,
		[DebitPrecedent] [decimal](20, 2) NOT NULL,
		[CreditPrecedent] [decimal](20, 2) NOT NULL,
		[Categorie] [tinyint] NOT NULL,
		[RulajDebit] [decimal](20, 2) NOT NULL,
		[RulajCredit] [decimal](20, 2) NOT NULL,
		[Sold] [decimal](20, 2) NOT NULL,
		[SortValue] [dbo].[TipCont] NOT NULL,
	CONSTRAINT [PK_'+@strContAn +'] PRIMARY KEY CLUSTERED(
		[Cont] ASC,
		[CodUnitate] ASC
	)) ON [PRIMARY]'
	
	IF @existTableCont = 0
		EXEC(@Comanda)
		
	SET @Comanda = 'ALTER TABLE [' + @strContAn +']  WITH CHECK ADD  CONSTRAINT [FK_'+@strContAn +'_' + @strContAn + '] FOREIGN KEY([ContParinte], [CodUnitate])
		REFERENCES ['+@strContAn+'] ([Cont], [CodUnitate])'
	IF @existTableCont = 0
		EXEC(@Comanda)
		
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] CHECK CONSTRAINT [FK_'+@strContAn +'_' + @strContAn + ']'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strContAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableCont = 0
		EXEC(@Comanda)	
		
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] CHECK CONSTRAINT [FK_'+@strContAn+'_Unitati]'
	IF @existTableCont = 0
		EXEC(@Comanda)	
		
		
	SET @Comanda = 'ALTER TABLE ['+@strContAn+']  WITH NOCHECK ADD  CONSTRAINT [CK_'+@strContAn+'_Tip] CHECK  (([Tip]=''A'' OR [Tip]=''P'' OR [Tip]=''B''))'
	IF @existTableCont = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] CHECK CONSTRAINT [CK_'+@strContAn+'_Tip]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Simbol]  DEFAULT ('''') FOR [Cont]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Denumire]  DEFAULT ('''') FOR [Denumire]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Tip]  DEFAULT (''A'') FOR [Tip]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Terminal]  DEFAULT ((1)) FOR [Terminal]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_CodContParinte]  DEFAULT ('''') FOR [ContParinte]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_EsteAnalitic]  DEFAULT ((1)) FOR [EsteAnalitic]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_DebitInitial]  DEFAULT ((0)) FOR [DebitInitial]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_CreditInitial]  DEFAULT ((0)) FOR [CreditInitial]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_DebitPrecedent]  DEFAULT ((0)) FOR [DebitPrecedent]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_CreditPrecedent]  DEFAULT ((0)) FOR [CreditPrecedent]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Categorie]  DEFAULT ((0)) FOR [Categorie]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_RulajDebit]  DEFAULT ((0)) FOR [RulajDebit]'
	IF @existTableCont = 0
		EXEC(@Comanda)
	
	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_RulajCredit]  DEFAULT ((0)) FOR [RulajCredit]'
	IF @existTableCont = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_Sold]  DEFAULT ((0)) FOR [Sold]'
	IF @existTableCont = 0
		EXEC(@Comanda)	

	SET @Comanda = 'ALTER TABLE ['+@strContAn+'] ADD  CONSTRAINT [DF_'+@strContAn+'_SortValue]  DEFAULT ('''') FOR [SortValue]'
	IF @existTableCont = 0
		EXEC(@Comanda)

	DECLARE @strAAAn varchar(40)
	DECLARE @existTableAA bit
	
	SET @strAAAn = 'ArticoleAliniate' + cast(@An AS varchar(4)) 
	SET @existTableAA = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strAAAn)
		SET @existTableAA = 1

	SET @Comanda = 'CREATE TABLE ['+@strAAAn+'](
	[ArtAl] [varchar](40) NOT NULL,
	[Denumire] [varchar](200) NOT NULL,
	[AAParinte] [varchar](40) NOT NULL,
	[Terminal] [bit] NOT NULL,
	[Titlu] [varchar](100) NOT NULL,
	[Categorii] [varchar](50) NOT NULL,
	[TermDenumire] [varchar](100) NOT NULL,
	[StartDenumire] [varchar](100) NOT NULL,
	[Anexa6] [bit] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	CONSTRAINT [PK_'+@strAAAn+'] PRIMARY KEY CLUSTERED(
		[ArtAl] ASC,
		[CodUnitate] ASC
	)) ON [PRIMARY]'
	IF @existTableAA = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strAAAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strAAAn+'_'+@strAAAn+'] FOREIGN KEY([AAParinte], [CodUnitate])
		REFERENCES ['+@strAAAn+'] ([ArtAl], [CodUnitate])'
	IF @existTableAA = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE [dbo].['+@strAAAn+'] CHECK CONSTRAINT [FK_'+@strAAAn+'_'+@strAAAn+']'
	IF @existTableAA = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE [dbo].['+@strAAAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strAAAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableAA = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE [dbo].['+@strAAAn+'] CHECK CONSTRAINT [FK_'+@strAAAn+'_Unitati]'
	IF @existTableAA = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE [dbo].['+@strAAAn+'] ADD  CONSTRAINT [DF_'+@strAAAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableAA = 0
		EXEC(@Comanda)

	---Bilant----------------------------
	DECLARE @strBilantAn varchar(40)
	DECLARE @existTableBilant bit
	
	SET @strBilantAn = 'Bilant' + cast(@An AS varchar(4)) 
	SET @existTableBilant = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strBilantAn)
		SET @existTableBilant = 1

	SET @Comanda = 'CREATE TABLE ['+@strBilantAn+'](
	[row] [int] NOT NULL,
	[nr_rand] [text] NOT NULL,
	[text] [text] NOT NULL,
	[codfix] [int] NOT NULL,
	[cod] [varchar](10) NOT NULL,
	[coltypei] [char](1) NOT NULL,
	[soldi] [text] NOT NULL,
	[coltypef] [char](1) NOT NULL,
	[soldf] [text] NOT NULL,
	[eval] [int] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	[Boldat] [bit] NOT NULL,
	CONSTRAINT [PK_'+@strBilantAn+'] PRIMARY KEY CLUSTERED( 
		[row] ASC)
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'
	IF @existTableBilant = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strBilantAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strBilantAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableBilant = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strBilantAn+'] CHECK CONSTRAINT [FK_'+@strBilantAn+'_Unitati]'
	IF @existTableBilant = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strBilantAn+'] ADD  CONSTRAINT [DF_'+@strBilantAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableBilant = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strBilantAn+'] ADD  CONSTRAINT [DF_'+@strBilantAn+'_Boldat]  DEFAULT ((0)) FOR [Boldat]'
	IF @existTableBilant = 0
		EXEC(@Comanda)

	---Conturi Valuta--------------------
	
	DECLARE @strContValutaAn varchar(40)
	DECLARE @existTableContValuta bit
	
	SET @strContValutaAn = 'ConturiValuta' + cast(@An AS varchar(4)) 
	SET @existTableContValuta = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strContValutaAn)
		SET @existTableContValuta = 1

	SET @Comanda = 'CREATE TABLE ['+@strContValutaAn+'](
	[CodValuta] [smallint] NOT NULL,
	[Cont] [dbo].[TipCont] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	[DebitInitial] [decimal](20, 2) NOT NULL,
	[CreditInitial] [decimal](20, 2) NOT NULL,
	[DebitPrecedent] [decimal](20, 2) NOT NULL,
	[CreditPrecedent] [decimal](20, 2) NOT NULL,
	[IdJurnal] [int] NOT NULL,
	CONSTRAINT [PK_'+@strContValutaAn+'] PRIMARY KEY CLUSTERED(
	[CodValuta] ASC,
	[Cont] ASC,
	[CodUnitate] ASC,
	[IdJurnal] ASC)) ON [PRIMARY]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strContValutaAn+'_'+@strContAn+'] FOREIGN KEY([Cont], [CodUnitate])
		REFERENCES ['+@strContAn+'] ([Cont], [CodUnitate])'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] CHECK CONSTRAINT [FK_'+@strContValutaAn+'_'+@strContAn+']'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strContValutaAn+'_Jurnale] FOREIGN KEY([IdJurnal])
		REFERENCES [dbo].[Jurnale] ([IDJurnal])'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] CHECK CONSTRAINT [FK_'+@strContValutaAn+'_Jurnale]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strContValutaAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] CHECK CONSTRAINT [FK_'+@strContValutaAn+'_Unitati]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+']  WITH NOCHECK ADD  CONSTRAINT [FK_'+@strContValutaAn+'_Valuta] FOREIGN KEY([CodValuta])
		REFERENCES [dbo].[Valuta] ([CodValuta])'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] CHECK CONSTRAINT [FK_'+@strContValutaAn+'_Valuta]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_CodValuta]  DEFAULT ((0)) FOR [CodValuta]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_DebitInitial]  DEFAULT ((0)) FOR [DebitInitial]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_CreditInitial]  DEFAULT ((0)) FOR [CreditInitial]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_DebitPrecedent]  DEFAULT ((0)) FOR [DebitPrecedent]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_CreditPrecedent]  DEFAULT ((0)) FOR [CreditPrecedent]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strContValutaAn+'] ADD  CONSTRAINT [DF_'+@strContValutaAn+'_IdJurnal]  DEFAULT ((0)) FOR [IdJurnal]'
	IF @existTableContValuta = 0
		EXEC(@Comanda)

	---Jurnale Solduri Initiale--------------------
	
	DECLARE @strJurnaleSIAn varchar(40)
	DECLARE @existTableJurnaleSI bit
	
	SET @strJurnaleSIAn = 'JurnaleSolduriInitiale' + cast(@An AS varchar(4)) 
	SET @existTableJurnaleSI = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strJurnaleSIAn)
		SET @existTableJurnaleSI = 1

	SET @Comanda = 'CREATE TABLE ['+@strJurnaleSIAn+'](
	[IDJurnal] [int] NOT NULL,
	[Cont] [dbo].[TipCont] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	[DebitInitial] [decimal](18, 2) NOT NULL,
	[CreditInital] [decimal](18, 2) NOT NULL,
	[DebitPrecedent] [decimal](20, 2) NOT NULL,
	[CreditPrecedent] [decimal](20, 2) NOT NULL,
	CONSTRAINT [PK_'+@strJurnaleSIAn+'] PRIMARY KEY CLUSTERED 
	(
	[IDJurnal] ASC,
	[Cont] ASC,
	[CodUnitate] ASC
	)) ON [PRIMARY]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strJurnaleSIAn+'_' + @strContAn + '] FOREIGN KEY([Cont], [CodUnitate])
		REFERENCES [' + @strContAn + '] ([Cont], [CodUnitate])'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] CHECK CONSTRAINT [FK_'+@strJurnaleSIAn+'_' + @strContAn + ']'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strJurnaleSIAn+'_Jurnale] FOREIGN KEY([IDJurnal])
		REFERENCES [Jurnale] ([IDJurnal])'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] CHECK CONSTRAINT [FK_'+@strJurnaleSIAn+'_Jurnale]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strJurnaleSIAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [Unitati] ([CodUnitate])'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] CHECK CONSTRAINT [FK_'+@strJurnaleSIAn+'_Unitati]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] ADD  CONSTRAINT [DF_'+@strJurnaleSIAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] ADD  CONSTRAINT [DF_'+@strJurnaleSIAn+'_DebitInitial]  DEFAULT ((0)) FOR [DebitInitial]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] ADD  CONSTRAINT [DF_'+@strJurnaleSIAn+'_DebitPrecedent]  DEFAULT ((0)) FOR [DebitPrecedent]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strJurnaleSIAn+'] ADD  CONSTRAINT [DF_'+@strJurnaleSIAn+'_CreditPrecedent]  DEFAULT ((0)) FOR [CreditPrecedent]'
	IF @existTableJurnaleSI = 0
		EXEC(@Comanda)

	---Ordonantari--------------------
	
	DECLARE @strOrdonantariAn varchar(40)
	DECLARE @existTableOrdonantari bit
	
	SET @strOrdonantariAn = 'Ordonantari' + cast(@An AS varchar(4)) 
	SET @existTableOrdonantari = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strOrdonantariAn)
		SET @existTableOrdonantari = 1

	SET @Comanda = 'CREATE TABLE ['+@strOrdonantariAn+'](
	[NrDoc] [decimal](18, 0) NOT NULL,
	[DataDoc] [datetime] NOT NULL,
	[IDFurnizor] [bigint] NOT NULL,
	[ValoareLei] [decimal](20, 2) NOT NULL,
	[IDJurnal] [int] NOT NULL,
	[Scop] [varchar](100) NOT NULL,
	[DocJust] [varchar](50) NOT NULL,
	[AngLegal] [varchar](50) NOT NULL,
	[Achitat] [bit] NOT NULL,
	[IdOrdonantare] [int] NOT NULL,
	[CodUnitate] [smallint] NOT NULL DEFAULT 0,
	[IdModPlata] [int] NOT NULL DEFAULT 1,
	[TotalDatorat] [decimal](18, 2) NOT NULL DEFAULT 0,
	[TotalAvansuri] [decimal](18, 2) NOT NULL DEFAULT 0,
	[ArtAl] [varchar](40) NOT NULL DEFAULT '''',
	[VizatCFP] [bit] NOT NULL,
	[MotivRefuz] [varchar](250) NOT NULL DEFAULT '''',
	[IDResponsabil] [int] NOT NULL DEFAULT 0,
	[DataVizaCFP] [datetime] NOT NULL DEFAULT (getdate()),
	[NrRegCFP] [varchar](20) NOT NULL DEFAULT (''FARA''),
	[IBANSursa] [varchar](24) NULL,
	[IBANDest] [varchar](24) NULL,
	[IDDocumentPlata] [int] NULL,
	CONSTRAINT [PK_'+@strOrdonantariAn+'] PRIMARY KEY CLUSTERED 
	(
		[IdOrdonantare] ASC
	),
	CONSTRAINT [FK_'+@strOrdonantariAn+'_'+@strAAAn+'] FOREIGN KEY([ArtAl], [CodUnitate]) REFERENCES ['+@strAAAn+'] ([ArtAl], [CodUnitate]),
	CONSTRAINT [FK_'+@strOrdonantariAn+'_Parteneri] FOREIGN KEY([IDfurnizor]) REFERENCES [dbo].[Parteneri] ([IdPartener]),
	CONSTRAINT [FK_'+@strOrdonantariAn+'_Jurnale] FOREIGN KEY([IDJurnal]) REFERENCES [dbo].[Jurnale] ([IDJurnal]),
	CONSTRAINT [FK_'+@strOrdonantariAn+'_ModPlata] FOREIGN KEY([IdModPlata]) REFERENCES [dbo].[ModPlata] ([IDModPlata]),
	CONSTRAINT [FK_'+@strOrdonantariAn+'_Unitati] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])	
	) ON [PRIMARY]'
	IF @existTableOrdonantari = 0
		EXEC(@Comanda)

	
	---RezultatPatrimonial--------------------
	
	DECLARE @strRezultatPatrimonialAn varchar(40)
	DECLARE @existTableRezultatPatrimonial bit
	
	SET @strRezultatPatrimonialAn = 'RezultatPatrimonial' + cast(@An AS varchar(4)) 
	SET @existTableRezultatPatrimonial = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strRezultatPatrimonialAn)
		SET @existTableRezultatPatrimonial = 1

	SET @Comanda = 'CREATE TABLE ['+@strRezultatPatrimonialAn+'](
	[row] [int] NOT NULL,
	[nr_rand] [text] NOT NULL,
	[text] [text] NOT NULL,
	[codfix] [int] NOT NULL,
	[cod] [varchar](10) NOT NULL,
	[coltypei] [char](1) NOT NULL,
	[soldi] [text] NOT NULL,
	[coltypef] [char](1) NOT NULL,
	[soldf] [text] NOT NULL,
	[eval] [int] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	[Boldat] [bit] NOT NULL,
	CONSTRAINT [PK_'+@strRezultatPatrimonialAn+'] PRIMARY KEY CLUSTERED 
	(
	[row] ASC
	)) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'
	IF @existTableRezultatPatrimonial = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRezultatPatrimonialAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strRezultatPatrimonialAn+'_Unitati] FOREIGN KEY([CodUnitate])
	REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableRezultatPatrimonial = 0
		EXEC(@Comanda)
	

	SET @Comanda = 'ALTER TABLE ['+@strRezultatPatrimonialAn+'] CHECK CONSTRAINT [FK_'+@strRezultatPatrimonialAn+'_Unitati]'
	IF @existTableRezultatPatrimonial = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRezultatPatrimonialAn+'] ADD  CONSTRAINT [DF_'+@strRezultatPatrimonialAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableRezultatPatrimonial = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRezultatPatrimonialAn+'] ADD  CONSTRAINT [DF_'+@strRezultatPatrimonialAn+'_Boldat]  DEFAULT ((0)) FOR [Boldat]'
	IF @existTableRezultatPatrimonial = 0
		EXEC(@Comanda)

	---RulajeDoc--------------------
	
	DECLARE @strRulajeDocAn varchar(40)
	DECLARE @existTableRulajeDoc bit
	
	SET @strRulajeDocAn = 'RulajeDoc' + cast(@An AS varchar(4)) 
	SET @existTableRulajeDoc = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strRulajeDocAn)
		SET @existTableRulajeDoc = 1

	SET @Comanda = 'CREATE TABLE ['+@strRulajeDocAn+'](
	[IDDocument] [bigint] NOT NULL,
	[ValoareLei] [decimal](20, 2) NOT NULL,
	[ValoareValuta] [decimal](20, 2) NOT NULL,
	[NumarDoc] [decimal](18, 0) NOT NULL,
	[DataDoc] [datetime] NOT NULL,
	[NumarNota] [varchar](50) NOT NULL,
	[TipFormula] [smallint] NOT NULL,
	[IDJurnal] [int] NULL,
	[Observatii] [varchar](200) NULL,
	[xUser] [varchar](50) NOT NULL,
	[xHost] [varchar](50) NOT NULL,
	[xDate] [datetime] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	CONSTRAINT [PK_'+@strRulajeDocAn+'] PRIMARY KEY CLUSTERED 
	(
	[IDDocument] ASC
	)) ON [PRIMARY]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+']  WITH NOCHECK ADD  CONSTRAINT [FK_'+@strRulajeDocAn+'_Jurnale] FOREIGN KEY([IDJurnal])
	REFERENCES [Jurnale] ([IDJurnal])'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] CHECK CONSTRAINT [FK_'+@strRulajeDocAn+'_Jurnale]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strRulajeDocAn+'_Unitati] FOREIGN KEY([CodUnitate])
	REFERENCES [Unitati] ([CodUnitate])'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] CHECK CONSTRAINT [FK_'+@strRulajeDocAn+'_Unitati]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+']  WITH NOCHECK ADD  CONSTRAINT [CK_'+@strRulajeDocAn+'_Tip_FORMULA] CHECK  (([TipFormula] = 3 or ([TipFormula] = 2 or ([TipFormula] = 1 or [TipFormula] = 0))))'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] CHECK CONSTRAINT [CK_'+@strRulajeDocAn+'_Tip_FORMULA]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_ValoareLei]  DEFAULT (0) FOR [ValoareLei]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_ValoareValuta]  DEFAULT (0) FOR [ValoareValuta]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_NumarDoc]  DEFAULT (0) FOR [NumarDoc]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_DataDoc]  DEFAULT (getdate()) FOR [DataDoc]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_NumarNota]  DEFAULT ('''') FOR [NumarNota]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_TipFormula]  DEFAULT (0) FOR [TipFormula]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_IDJurnal]  DEFAULT (0) FOR [IDJurnal]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_xUser]  DEFAULT (suser_sname()) FOR [xUser]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_xHost]  DEFAULT (host_name()) FOR [xHost]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_xDate]  DEFAULT (0) FOR [xDate]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeDocAn+'] ADD  CONSTRAINT [DF_'+@strRulajeDocAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableRulajeDoc = 0
		EXEC(@Comanda)

	---Rulaje--------------------
	
	DECLARE @strRulajeAn varchar(40)
	DECLARE @existTableRulaje bit
	
	SET @strRulajeAn = 'Rulaje' + cast(@An AS varchar(4)) 
	SET @existTableRulaje = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strRulajeAn)
		SET @existTableRulaje = 1

	SET @Comanda = 'CREATE TABLE ['+@strRulajeAn+'](
	[CodFormula] [bigint] NOT NULL,
	[ContDebit] [dbo].[TipCont] NOT NULL,
	[ContCredit] [dbo].[TipCont] NOT NULL,
	[CodValuta] [smallint] NOT NULL,
	[IDDocument] [bigint] NOT NULL,
	[ValoareValuta] [decimal](20, 2) NOT NULL,
	[Curs] [decimal](18, 4) NOT NULL,
	[ValoareLei] [decimal](20, 2) NOT NULL,
	[DataDocJust] [datetime] NOT NULL,
	[TipDocJust] [varchar](10) NOT NULL,
	[NumarDocJust] [decimal](18, 0) NOT NULL,
	[ExplicatiiDocJust] [varchar](200) NOT NULL,
	[NrCrt] [smallint] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	CONSTRAINT [PK_'+@strRulajeAn+'] PRIMARY KEY CLUSTERED 
	(
	[CodFormula] ASC
	)) ON [PRIMARY]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strRulajeAn+'_'+@strContAn+'_Credit] FOREIGN KEY([ContCredit], [CodUnitate])
	REFERENCES ['+@strContAn+'] ([Cont], [CodUnitate])'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] CHECK CONSTRAINT [FK_'+@strRulajeAn+'_'+@strContAn+'_Credit]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)
		
	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strRulajeAn+'_'+@strContAn+'_Debit] FOREIGN KEY([ContDebit], [CodUnitate])
		REFERENCES ['+@strContAn+'] ([Cont], [CodUnitate])'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] CHECK CONSTRAINT [FK_'+@strRulajeAn+'_'+@strContAn+'_Debit]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+']  WITH NOCHECK ADD  CONSTRAINT [FK_'+@strRulajeAn+'_'+@strRulajeDocAn+'] FOREIGN KEY([IDDocument])
		REFERENCES ['+@strRulajeDocAn+'] ([IDDocument])
		ON UPDATE CASCADE
		ON DELETE CASCADE'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] CHECK CONSTRAINT [FK_'+@strRulajeAn+'_'+@strRulajeDocAn+']'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+']  WITH CHECK ADD  CONSTRAINT [FK_'+@strRulajeAn+'_Unitati] FOREIGN KEY([CodUnitate])
		REFERENCES [dbo].[Unitati] ([CodUnitate])'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] CHECK CONSTRAINT [FK_'+@strRulajeAn+'_Unitati]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+']  WITH NOCHECK ADD  CONSTRAINT [FK_'+@strRulajeAn+'_Valuta] FOREIGN KEY([CodValuta])
	REFERENCES [dbo].[Valuta] ([CodValuta])'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] CHECK CONSTRAINT [FK_'+@strRulajeAn+'_Valuta]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_CodValuta]  DEFAULT (0) FOR [CodValuta]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_ValareaValuta]  DEFAULT (0) FOR [ValoareValuta]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_Curs]  DEFAULT (1) FOR [Curs]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_ValoareLei]  DEFAULT (0) FOR [ValoareLei]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_TipDocJust]  DEFAULT (''NC'') FOR [TipDocJust]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_NrCrt]  DEFAULT (1) FOR [NrCrt]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)

	SET @Comanda = 'ALTER TABLE ['+@strRulajeAn+'] ADD  CONSTRAINT [DF_'+@strRulajeAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableRulaje = 0
		EXEC(@Comanda)
		
	---VenituriSiCheltuieli--------------------
	
	DECLARE @strVenituriSiCheltuieliAn varchar(40)
	DECLARE @existTableVenituriSiCheltuieli bit
	
	SET @strVenituriSiCheltuieliAn = 'VenituriSiCheltuieli' + cast(@An AS varchar(4)) 
	SET @existTableVenituriSiCheltuieli = 0
	IF EXISTS(SELECT * FROM sys.tables WHERE NAME LIKE @strVenituriSiCheltuieliAn)
		SET @existTableVenituriSiCheltuieli = 1

	SET @Comanda = 'CREATE TABLE ['+@strVenituriSiCheltuieliAn+'](
	[row] [int] NOT NULL,
	[nr_rand] [text] NOT NULL,
	[text] [text] NOT NULL,
	[codfix] [int] NOT NULL,
	[cod] [varchar](20) NOT NULL,
	[coltypei] [char](1) NOT NULL,
	[soldi] [text] NOT NULL,
	[coltypef] [char](1) NOT NULL,
	[soldf] [text] NOT NULL,
	[eval] [int] NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	[Boldat] [bit] NOT NULL,
	CONSTRAINT [PK_'+@strVenituriSiCheltuieliAn+'] PRIMARY KEY CLUSTERED 
	(
	[row] ASC
	)) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'
	IF @existTableVenituriSiCheltuieli = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strVenituriSiCheltuieliAn+'] ADD  CONSTRAINT [DF_'+@strVenituriSiCheltuieliAn+'_CodUnitate]  DEFAULT ((0)) FOR [CodUnitate]'
	IF @existTableVenituriSiCheltuieli = 0
		EXEC(@Comanda)


	SET @Comanda = 'ALTER TABLE ['+@strVenituriSiCheltuieliAn+'] ADD  CONSTRAINT [DF_'+@strVenituriSiCheltuieliAn+'_Boldat]  DEFAULT ((0)) FOR [Boldat]'
	IF @existTableVenituriSiCheltuieli = 0
		EXEC(@Comanda)
		

END

GO


DELETE FROM [admin_ApplicationMenu] WHERE [ApplicationId]='E03B2883-43E3-41B7-A41E-A620126D1BE0'
SET IDENTITY_INSERT [admin_ApplicationMenu] ON
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(75,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Proces Verbal CM',1074,1,'TiparirePV',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(94,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Stat de functii',1074,2,'StatDeFunctii',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(95,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Export declaratii',1074,3,'ExportDeclaratii',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1052,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Personal',NULL,10,'Gestiune_Personal',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1053,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Concedii Medicale',NULL,30,'CertificateMedicale',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1054,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Pontaje, Adaosuri, Diminuari',NULL,20,'Pontaje',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1055,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Nomenclatoare',NULL,40,NULL,NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1056,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Setari',NULL,50,NULL,NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1057,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Parametrizare modul',NULL,70,'ParametrizareModul',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1058,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Recalcul Salarii',NULL,80,'CalculSalarii',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1059,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Despre modul',NULL,90,NULL,NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1060,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Interventii IT',NULL,85,'Calculatoare',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1065,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Documente Scanate',NULL,60,'Scanare_Documente',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1074,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Liste',NULL,60,NULL,NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1159,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Departamente',1055,20,'Departamente',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1160,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Ocupatii',1055,21,'Nomenclatoare_Ocupatii',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1161,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Judete',1055,22,'Nomenclatoare_Judete',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1162,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Localitati',1055,23,'Nomenclatoare_Localitati',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1163,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Case Asigurari Sanatate',1055,24,'Nomenclatoare_CaseAsigSanatate',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1164,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Tipuri Documente Scanate',1055,26,'Tipuri_Documente_Scanate',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1172,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Grile',1055,25,'Grile',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1264,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Studii',1056,40,'Nomenclatoare_TipStudii',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1265,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Contracte',1056,41,'Nomenclatoare_TipContracte',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1266,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Departamente',1056,42,'Tipuri_Departamente',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1267,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Grade(Trepte  Profesionale)',1056,43,'Nomenclatoare_TipGrad',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1268,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Specialitati',1056,44,'TipSpecialitati',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1269,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Prezenta',1056,45,'TipPrezenta',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1271,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Sporuri',1056,47,'TipuriSporuri',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1272,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Retineri',1056,48,'TipuriRetineri',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1273,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Adaosuri, diminuari',1056,49,'TipuriAdaos',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(1274,'E03B2883-43E3-41B7-A41E-A620126D1BE0','Import',1056,50,'Import',NULL,NULL)
SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[dsc_GenDecl205]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[dsc_GenDecl205]
GO


CREATE PROCEDURE [dbo].[dsc_GenDecl205]
	@an int,
	@totBC decimal(15,0) OUT,
	@totI decimal(15,0) OUT,
	@nrBen int OUT
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    SET @totBC = 0
    SET  @totI = 0
	SET @nrBen = 0



	select @nrBen=COUNT(Distinct a.Marca) FROM
	dbo.pArhPersSal AS a LEFT OUTER JOIN
    pPerson c on a.Marca = c.marca AND a.Cod_Unit = c.Cod_Unit
	where a.anul=@an


	select @totBC=SUM(ROUND(a.VenitBC, 0)),@totI=SUM(a.Impozit) FROM
	dbo.pArhPersSal AS a INNER JOIN
             dbo.pArhExtensii AS b ON a.Marca = b.marca AND a.Luna = b.Luna AND a.Anul = b.Anul AND a.Cod_Unit = b.Cod_Unit  JOIN
             pPerson c on a.Marca = c.marca AND a.Cod_Unit = c.Cod_Unit
	where a.anul=@an


    SELECT   MAX(a.Nume_Pren) Nume_Pren,c.CNP,a.Anul,CASE WHEN a.TipContr=0 THEN 1 ELSE 2 END TipContr, SUM(a.CastigBrut) AS VenitBrutAnual,SUM(a.DedPersBz) AS DeduceriPersonale,
	SUM(a.DedSupli) AS Altededuceri,SUM(b.CotSind) AS CotSind, SUM(b.AlteDedEf) AS AlteDedEf,
	SUM(ROUND(a.VenitBC, 0)) AS VenitBC,SUM(a.Impozit) AS Impozit
	--TOP (100) PERCENT a.Marca, CASE WHEN a.Luna IS NULL THEN 'TOTAL' ELSE CASE WHEN LEN(LTRIM(RTRIM(CAST(a.Luna AS varchar(2))))) 
	--                      = 1 THEN '0' + LTRIM(RTRIM(CAST(a.Luna AS varchar(2)))) ELSE LTRIM(RTRIM(CAST(a.Luna AS varchar(2)))) END END AS Luna, SUM(a.CastigBrut) AS Brut, SUM(a.DedPersBz) AS DedPersBz, 
	--                      SUM(a.DedSupli) AS DedSupli, SUM(ROUND(a.VenitBC, 0)) AS VenitBC, SUM(a.Impozit) AS Impozit, SUM(a.NrPrsIntr) AS NrPrsIntr, SUM(b.CotSind) AS CotSind, SUM(b.AlteDedEf) AS AlteDedEf
	FROM         dbo.pArhPersSal AS a INNER JOIN
             dbo.pArhExtensii AS b ON a.Marca = b.marca AND a.Luna = b.Luna AND a.Anul = b.Anul AND a.Cod_Unit = b.Cod_Unit  JOIN
             pPerson c on a.Marca = c.marca AND a.Cod_Unit = c.Cod_Unit  
	where a.anul=@an
	GROUP BY c.CNP, a.Anul,CASE WHEN a.TipContr=0 THEN 1 ELSE 2 END
	ORDER BY c.CNP, a.Anul,CASE WHEN a.TipContr=0 THEN 1 ELSE 2 END

END

GO



DELETE FROM [admin_ApplicationMenu] WHERE [ApplicationId]='B687EA0D-80F8-4F86-A87A-5242188B83A7'
SET IDENTITY_INSERT [admin_ApplicationMenu] ON
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(44,'B687EA0D-80F8-4F86-A87A-5242188B83A7','Meniuri',NULL,3,'Meniuri',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(45,'B687EA0D-80F8-4F86-A87A-5242188B83A7','Aplicatii',NULL,1,'Aplicatii',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(46,'B687EA0D-80F8-4F86-A87A-5242188B83A7','Utilizatori si Roluri',NULL,2,'RoluriUtilizatori',NULL,NULL)
INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(47,'B687EA0D-80F8-4F86-A87A-5242188B83A7','Interogare',NULL,4,'Interogare',NULL,NULL)
SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
GO


DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='8489910A-6599-436A-B3E5-21B6DB74A7BE' AND [HandlerName]='Registrul_Ordonantari'
IF @Cate= 0 
begin
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2670,'8489910A-6599-436A-B3E5-21B6DB74A7BE','Registrul ordonantarilor',2087,206,'Registrul_Ordonantari',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF	
end 
go


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[exbug_RegistrulOrdonantari]'))
DROP VIEW [dbo].[exbug_RegistrulOrdonantari]
GO

CREATE VIEW [dbo].[exbug_RegistrulOrdonantari]
AS
SELECT     NrDoc, DataDoc, ValoareLei, Scop, DocJust, ArtAl,CodUnitate
FROM         dbo.Ordonantari

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GenListaExecutieChelt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GenListaExecutieChelt]
GO


CREATE PROCEDURE [dbo].[GenListaExecutieChelt]   
@idLista smallint, @CodUnitate smallint, 
@An varchar(4)
AS

DECLARE @dataUI as float, @dtDataStartUI as datetime,@dtDataEndUI as datetime
DECLARE @strContStart as TipCont,@strContEnd as TipCont
DECLARE @strDataStart as varchar(50), @strDataEnd as varchar(50)
DECLARE @strCapitol as varchar(100)
DECLARE @tabela varchar(100)
DECLARE @categorie as tinyint
DECLARE @strcategorie as varchar(10)
DECLARE @tipb as varchar(10)
DECLARE @analitica bit
DECLARE @cfm bit
DECLARE @fni bit
DECLARE @centr bit
DECLARE @idJurn smallint
DECLARE @strFiltruCapitol varchar(200)

SET @idJurn = -1
SET @categorie = 0
SET @strcategorie = '0'
SET @analitica = 0
SET @cfm = 0
SET @fni = 0
SET @centr = 0

SELECT @strDataStart=Valoare FROM [ParamListe] WHERE IDLista=@idLista AND Cod='DLD' AND [User]=suser_sname() AND [Host]=host_name() AND [CodUnitate]=@CodUnitate
SET @strDataStart = LTRIM(@strDataStart)
SET @strDataStart = RTRIM(@strDataStart)
IF LEN(@strDataStart)<>0
BEGIN
	SET @dtDataStartUI = CAST(CAST(@strDataStart AS float)-2  AS datetime)
	SET @strDataStart = ''''+CAST(@dtDataStartUI AS varchar(50))+''''
END

SELECT @strDataEnd=Valoare FROM [ParamListe] WHERE IDLista=@idLista AND Cod='PLD' AND [User]=suser_sname() AND [Host]=host_name()  AND [CodUnitate]=@CodUnitate
SET @strDataEnd = LTRIM(@strDataEnd)
SET @strDataEnd = RTRIM(@strDataEnd)

IF LEN(@strDataEnd)<>0
BEGIN
	SET @dtDataEndUI = CAST(CAST(@strDataEnd AS float)-2 AS datetime)
	SET @strDataEnd = ''''+CAST(@dtDataEndUI AS varchar(50))+''''
END

SELECT @strContStart=Valoare FROM [ParamListe] WHERE IDLista=@idLista AND Cod='DLC' AND [User]=suser_sname() AND [Host]=host_name()  AND [CodUnitate]=@CodUnitate
SELECT @strContEnd=Valoare FROM [ParamListe] WHERE IDLista=@idLista AND Cod='PLC' AND [User]=suser_sname() AND [Host]=host_name()  AND [CodUnitate]=@CodUnitate



--conturi fara miscari
SET @tipb='0'
SELECT @tipb=Valoare FROM [ParamListe] WHERE IDLista=@idLista AND Cod='CFM' AND [User]=suser_sname() AND [Host]=host_name()  AND [CodUnitate]=@CodUnitate
if @tipb='1'
	SET @cfm =1

SET @tipb='0'
SELECT @tipb=Valoare FROM [ParamListe] WHERE IDLista=@idLista AND Cod='FNI' AND [User]=suser_sname() AND [Host]=host_name()  AND [CodUnitate]=@CodUnitate
if @tipb='1'
	SET @fni =1

SET @tipb='0'
SELECT @tipb=Valoare FROM [ParamListe] WHERE IDLista=@idLista AND Cod='CNT' AND [User]=suser_sname() AND [Host]=host_name()  AND [CodUnitate]=@CodUnitate
if @tipb='1'
	SET @centr =1

SELECT @strCapitol=Valoare FROM [ParamListe] WHERE IDLista=@idLista AND Cod='JRN' AND [User]=suser_sname() AND [Host]=host_name() AND [CodUnitate]=@CodUnitate
SELECT @idJurn = IDJurnal FROM [Jurnale] WHERE [Codificare]=@strCapitol  AND [CodUnitate]=@CodUnitate
	
SET @strFiltruCapitol = ''
if @idJurn>0 AND @idJurn is NOT NULL
	SET @strFiltruCapitol = ' AND IDJurnal='+cast(@idJurn as varchar(10))



IF  EXISTS(SELECT * FROM tempdb..SysObjects WHERE name = '#balanta' AND type = 'U')	
BEGIN
	DROP TABLE  #balanta
	IF @@ERROR != 0 GOTO EROARE				
END

DECLARE @ca varchar(1000)
DECLARE @ab varchar(1000)
DECLARE @al varchar(1000)
DECLARE @det varchar(1000)
DECLARE @plati varchar(1000)
DECLARE @chelt varchar(2000)
DECLARE @toate varchar(6000)

SET @det =','
SET @plati =','
SET @chelt =','
SET @ca =','
SET @al =','
SET @ab =','

SELECT @det=@det + Cont + ',' FROM ConturiSpeciale WHERE Tipuri like'%{CD}%' AND [CodUnitate]=@CodUnitate
SELECT @ca=@ca + Cont + ',' FROM ConturiSpeciale WHERE Tipuri like'%{CA}%'  AND [CodUnitate]=@CodUnitate
SELECT @ab=@ab + Cont + ',' FROM ConturiSpeciale WHERE Tipuri like'%{AB}%'  AND [CodUnitate]=@CodUnitate
SELECT @al=@al + Cont + ',' FROM ConturiSpeciale WHERE Tipuri like'%{AL}%' AND [CodUnitate]=@CodUnitate 
SELECT @plati=@plati + Cont + ',' FROM ConturiSpeciale WHERE Tipuri like'%{AA}%' AND Cont LIKE '7%'  AND [CodUnitate]=@CodUnitate
SELECT @chelt=@chelt +  Cont + ',' FROM ConturiSpeciale WHERE Tipuri like'%{AA}%' AND Cont LIKE '6%'  AND [CodUnitate]=@CodUnitate
SET @toate = @det+@chelt+@plati+@ca+@ab+@al


CREATE TABLE [#balanta_t] (
	[ArtAl] varchar(50) NOT NULL, 
	[AAParinte] varchar(50) NOT NULL, 
	[Categorii] varchar(50) NOT NULL, 
	[Denumire] varchar(400) NOT NULL DEFAULT '',
	[Anexa6] bit NOT NULL DEFAULT 0,	
	[Terminal] bit NOT NULL,
	[Titlu] varchar(100) NOT NULL,

	[CrediteAprobate] DECIMAL(20,2) NOT NULL DEFAULT 0,
	[CrediteDeschise] DECIMAL(20,2) NOT NULL DEFAULT 0,
	[AngajamenteBugetare] DECIMAL(20,2) NOT NULL DEFAULT 0,
	[AngajamenteLegale] DECIMAL(20,2) NOT NULL DEFAULT 0,
	[PlatiNete] DECIMAL(20,2) NOT NULL DEFAULT 0,

	[DisponibilCredit] DECIMAL(20,2) NOT NULL DEFAULT 0,
	[Cheltuieli] DECIMAL(20,2) NOT NULL DEFAULT 0,
	[DebitInitial] DECIMAL(20,2) NOT NULL DEFAULT 0,
	[CreditInitial] DECIMAL(20,2) NOT NULL DEFAULT 0
)

DECLARE @strSelect	varchar(8000)
DECLARE @filtData varchar(500)
DECLARE @filtDataC varchar(500)
DECLARE @filtC varchar(500)
DECLARE @filtCC varchar(500)
DECLARE @strCodUnitate varchar(50)

SET @filtData = ''
SET @filtDataC = ''
SET @filtC = ''
SET @filtCC = ''
SET @strCodUnitate = CAST(@CodUnitate AS varchar(50))

IF @idLista = 1
	BEGIN
		IF LEN(@strDataEnd) <>0
			SET @filtData =  ' AND D.DataDoc <='+@strDataEnd		
	END
ELSE
	BEGIN
		IF LEN(@strDataStart) <>0
			SET @filtData =  ' AND D.DataDoc >='+@strDataStart
		IF LEN(@strDataEnd) <>0
			SET @filtData = @filtData + '  AND D.DataDoc <='+@strDataEnd	
	END
IF LEN(@strContStart) <>0
	SET @filtC =  '  AND F.ContDebit >='''+@strContStart + ''' '
IF LEN(@strContEnd) <>0
	SET @filtC = @filtC + ' AND F.ContDebit <='''+@strContEnd + ''' '

SET @filtData = @filtData + @filtC
IF @fni = 1
	SET @filtData =@filtData + '  AND F.TipDocJust <>''IC'' '  

SET @filtDataC = @filtData
SET @filtDataC = REPLACE(@filtDataC,'F.ContDebit','F.ContCredit') 
PRINT 'Total' + @filtDataC
SET @filtCC = REPLACE(@filtC,'F.ContDebit','Cont') 
SET @filtC = REPLACE(@filtC,'F.ContDebit','a.ArtAl') 

--	SUM(COALESCE(Cnt.[DebitInitial],0))  DebitInitial,
--	SUM(COALESCE(Cnt.[CreditInitial],0)) CreditInitial
--	Cnt.[DebitInitial],Cnt.[CreditInitial]

SET @strSelect =' INSERT INTO [#balanta_t]
	 SELECT a.ArtAl,a.AAParinte,a.Categorii,a.StartDenumire+a.Denumire+a.TermDenumire,a.Anexa6,a.Terminal,a.Titlu,
	SUM(COALESCE(Rul.CrediteAprobate,0)) CrediteAprobate, 
	SUM(COALESCE(Rul.CreditDeschis,0)) CrediteDeschise, 
	SUM(COALESCE(Rul.AngajamenteBugetare,0)) AngajamenteBugetare, 
	SUM(COALESCE(Rul.AngajamenteLegale+Cnt.[DebitInitial]-Cnt.[CreditInitial],0)) AngajamenteLegale, 
	SUM(COALESCE(Rul.PlatiNete,0)) PlatiNete,
	SUM(COALESCE(Rul.[CreditDeschis],0)) - SUM(COALESCE(Rul.PlatiNete,0)) DisponibilCredit,
	SUM(COALESCE(Rul.Cheltuieli,0)) Cheltuieli, 
	SUM(COALESCE(Cnt.[DebitInitial],0))  DebitInitial,
	SUM(COALESCE(Cnt.[CreditInitial],0)) CreditInitial
FROM [ArticoleAliniate] a LEFT OUTER JOIN 
(SELECT 
dbo.GetAnalitic(Cont) Cont,[CodUnitate],
sum(dbo.IsContInRetValoare('',''+dbo.GetSintetic(Cont)+'','','''+@al+''',DebitInitial)) DebitInitial,
sum(dbo.IsContInRetValoare('',''+dbo.GetSintetic(Cont)+'','','''+@al+''',CreditInitial)) CreditInitial
FROM
[Conturi'+@An+']
WHERE Terminal = 1 AND Cont<>''N/A''  AND  dbo.IsContIn('',''+ dbo.GetSintetic(Cont)+'','','''+@toate+''')<>0 ' + @filtCC + '
 AND [CodUnitate] = '+@strCodUnitate+'
GROUP BY dbo.GetAnalitic(Cont),[CodUnitate]) CNT
ON dbo.IsContInclus(a.ArtAl,CNT.Cont,a.Terminal)=1 AND a.[CodUnitate]=CNT.[CodUnitate]
LEFT OUTER JOIN
(SELECT  
			dbo.GetAnalitic(COALESCE(t2.ContCredit, t1.ContDebit)) Cont, 
			sum(dbo.IsContInRetValoare('',''+dbo.GetSintetic(COALESCE(t2.ContCredit, t1.ContDebit))+'','','''+@ca+''',SumaDebit)) CrediteAprobate, 
			sum(dbo.IsContInRetValoare('',''+dbo.GetSintetic(COALESCE(t2.ContCredit, t1.ContDebit))+'','','''+@det+''',SumaDebit)) CreditDeschis, 
			sum(dbo.IsContInRetValoare('',''+dbo.GetSintetic(COALESCE(t2.ContCredit, t1.ContDebit))+'','','''+@ab+''',SumaDebit)) AngajamenteBugetare, 
			sum(dbo.IsContInRetValoare('',''+dbo.GetSintetic(COALESCE(t2.ContCredit, t1.ContDebit))+'','','''+@al+''',SumaDebit)) AngajamenteLegale, 
			sum(dbo.IsContInRetValoare('',''+dbo.GetSintetic(COALESCE(t2.ContCredit, t1.ContDebit))+'','','''+@plati+''',COALESCE(SumaCredit,0)-COALESCE(SumaDebit,0))) PlatiNete, 
			sum(dbo.IsContInRetValoare('',''+dbo.GetSintetic(COALESCE(t2.ContCredit, t1.ContDebit))+'','','''+@chelt+''',SumaDebit)) Cheltuieli 
		FROM 
			(SELECT SUM(coalesce(F.ValoareLei,0)) sumaDebit, F.ContDebit 
			FROM [RulajeDoc'+@An+'] D INNER JOIN [Rulaje'+@An+'] F ON D.[IDDocument] = F.[IDDocument] 
			WHERE F.ContDebit<>''N/A''  AND  dbo.IsContIn('',''+ dbo.GetSintetic(F.ContDebit)+'','','''+@toate+''')<>0 '  + @filtData + @strFiltruCapitol +
			' AND D.[CodUnitate] = '+@strCodUnitate+
		' GROUP BY F.ContDebit) t1 
		FULL OUTER JOIN 
			(SELECT SUM(coalesce(F.ValoareLei,0)) sumaCredit, F.ContCredit
			FROM [RulajeDoc'+@An+'] D INNER JOIN [Rulaje'+@An+'] F ON D.[IDDocument] = F.[IDDocument] 
			WHERE F.ContCredit <>''N/A'' AND  dbo.IsContIn('',''+ dbo.GetSintetic(F.ContCredit)+'','','''+@toate+''')<>0 ' + @filtDataC + @strFiltruCapitol + ' 
			AND D.[CodUnitate] = '+@strCodUnitate+'
			 GROUP BY F.ContCredit) t2 
		ON t1.ContDebit = t2.ContCredit 
GROUP BY dbo.GetAnalitic(COALESCE(t2.ContCredit, t1.ContDebit))) RUL
ON  cnt.cont=rul.cont
WHERE   a.ArtAl <>''N/A'' ' + @filtC

SET @strSelect = @strSelect + ' GROUP BY  a.ArtAl,a.AAParinte,a.Categorii,a.StartDenumire,a.Denumire,a.TermDenumire,a.Anexa6,a.Terminal,a.Titlu ORDER BY a.ArtAl' 


--ON substring(rul.cont,1,len(c.cont))=c.cont


PRINT @strSelect
EXEC(@strSelect)
IF @@ERROR != 0 GOTO EROARE				

UPDATE [#balanta_t] SET [CrediteAprobate] = (SELECT SUM([CrediteAprobate]) FROM [#balanta_t] a WHERE a.AAParinte=[#balanta_t].ArtAl),
[CrediteDeschise] = (SELECT SUM([CrediteDeschise]) FROM [#balanta_t] a WHERE a.AAParinte=[#balanta_t].ArtAl),
[AngajamenteBugetare] = (SELECT SUM([AngajamenteBugetare]) FROM [#balanta_t] a WHERE a.AAParinte=[#balanta_t].ArtAl),
[AngajamenteLegale] = (SELECT SUM([AngajamenteLegale]) FROM [#balanta_t] a WHERE a.AAParinte=[#balanta_t].ArtAl),
[PlatiNete] = (SELECT SUM([PlatiNete]) FROM [#balanta_t] a WHERE a.AAParinte=[#balanta_t].ArtAl),
[DisponibilCredit] = (SELECT SUM([DisponibilCredit]) FROM [#balanta_t] a WHERE a.AAParinte=[#balanta_t].ArtAl),
[Cheltuieli] = (SELECT SUM([Cheltuieli]) FROM [#balanta_t] a WHERE a.AAParinte=[#balanta_t].ArtAl)
WHERE [Categorii]='[TOT]'


SET @strSelect ='INSERT INTO [#balanta_t]
SELECT ''0'',''0'',''0'',''0'',1,0,''TOTAL'', 
	SUM(COALESCE([CrediteAprobate],0)),
	SUM(COALESCE([CrediteDeschise],0)),
	SUM(COALESCE([AngajamenteBugetare],0)),
	SUM(COALESCE([AngajamenteLegale],0)),
	SUM(COALESCE([PlatiNete],0)),
	SUM(COALESCE([DisponibilCredit],0)),
	SUM(COALESCE([Cheltuieli],0)),
	SUM(COALESCE([DebitInitial],0)),
	SUM(COALESCE([CreditInitial],0))
FROM [#balanta_t] '

SET @strSelect=@strSelect + 'WHERE terminal=1'
EXEC(@strSelect)
IF @@ERROR != 0 GOTO EROARE	

if @centr=0
BEGIN
	if @cfm=0
	SELECT [ArtAl], 	[Denumire],[Terminal],[Titlu],[CrediteAprobate],[CrediteDeschise],[AngajamenteBugetare],[AngajamenteLegale],[PlatiNete],[DisponibilCredit],[Cheltuieli] FROM [#balanta_t] 
	WHERE [CrediteAprobate] <>0 OR [AngajamenteBugetare]<>0 OR [AngajamenteLegale]<>0 OR [CrediteDeschise] <> 0 OR [PlatiNete] <> 0 OR [Cheltuieli] != 0   
	ORDER BY ArtAl
	else
	SELECT [ArtAl], 	[Denumire],[Terminal],[Titlu],[CrediteAprobate],[CrediteDeschise],[AngajamenteBugetare],[AngajamenteLegale],[PlatiNete],[DisponibilCredit],[Cheltuieli] FROM [#balanta_t]
	ORDER BY ArtAl
END
ELSE
SELECT [ArtAl], 	[Denumire],[Terminal],[Titlu],[CrediteAprobate],[CrediteDeschise],[AngajamenteBugetare],[AngajamenteLegale],[PlatiNete],[DisponibilCredit],[Cheltuieli] FROM [#balanta_t]
WHERE [Categorii]='[TOT]' OR Anexa6=1   
ORDER BY ArtAl

GOTO Gata
EROARE:
	RAISERROR ('Eroare la generarea balantei',16,-1)
	GOTO Gata
EROARE1:
	RAISERROR ('Va rugam completati capitolul pentru lista curenta!!',16,-1)	
	GOTO Gata
Gata:
GO

IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[VerificaTotalDocument]'))
DROP TRIGGER [dbo].[VerificaTotalDocument]
GO


CREATE TRIGGER [dbo].[VerificaTotalDocument] 
   ON  [dbo].[DocumentePlataDetaliu]
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
	SET NOCOUNT ON;
	DECLARE @mesaj varchar(200)
	DECLARE @nrdoc varchar(200)
	DECLARE @SumaPlatita decimal(18,2), @sumaDatorata decimal(18,2)
	SET @nrdoc=''
	SET @SumaPlatita = 0
	SET @sumaDatorata = 0
	
	
	SELECT @nrdoc=MAX(d.NrDoc +  '/' +CONVERT(varchar(20),d.DataDoc,104)),  @SumaDatorata = MAX(ABS(d.Total)) ,
	  @SumaPlatita = MAX(ABS(pl.ValoarePlatita)) 
	FROM (SELECT dpd.IDDocument, SUM(ABS(dpd.Valoare)) ValoarePlatita, SUM(ABS(dpd.ValoareTVA)) ValoareTVAPlatita  FROM 
	DocumentePlataDetaliu dpd JOIN inserted i on i.IDDocument = dpd.IDDocument
	GROUP BY dpd.IDDocument) pl 
	JOIN Documente d ON pl.IDDocument = d.IDDocument  
	HAVING MAX(ABS(pl.ValoarePlatita))- MAX(ABS(d.Total)) >0  OR  
	MAX(ABS(pl.ValoareTVAPlatita)) - MAX(ABS(d.TotalValoareTVA)) >0
	
	IF @nrdoc<>''
		GOTO Error1
	
    GOTO Gata
	Error1:
	    SET @mesaj = 'Incasare/plata('+CAST(@SumaPlatita as varchar(25))+ ') mai mare decat totalul documentul incasat/platit ('+CAST(@sumaDatorata as varchar(25))+'): ' +@nrdoc
		RAISERROR (@mesaj, 16, 1)
		ROLLBACK TRANSACTION
	Gata:
END

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportDocumente]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportDocumente]
GO


CREATE PROCEDURE [dbo].[fares_FiltreazaRaportDocumente] 
    @filtruPart varchar(8000),
	@filtruArt varchar(8000),
	@filtruTipDoc varchar(8000),
	@data1 datetime,
	@data2 datetime,
	@DefalcatTVA bit,
	@receptie bit,
	@marfa bit,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

  SELECT * FROM [fares_DocumenteDimensiuni] WHERE 
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruTipDoc)))=0 OR (IDTipDocument IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruTipDoc,',') fart))) AND
    (@receptie=0 OR (@receptie=1 AND [TipOperatie] LIKE '%I%' AND IDTipDocument=0)) AND
    ((@marfa=0 AND [ValoareTotalaCuAdaos]=0) OR (@marfa=1 AND [ValoareTotalaCuAdaos]<>0)) AND 
	CodUnitate = @CodUnitate AND [DataDoc]>=@data1 AND [DataDoc]<=@data2
	ORDER BY [DataDoc]
END


GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportOpConturi]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportOpConturi]
GO


CREATE PROCEDURE [dbo].[fares_FiltreazaRaportOpConturi] 
    @filtruPart varchar(8000),
	@filtruArt varchar(8000),
	@filtruTipDoc varchar(2000),
	@data1 datetime,
	@data2 datetime,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

  SELECT * FROM [fares_DocumenteDimConturi] WHERE 
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruTipDoc)))=0 OR (IDTipDocument IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruTipDoc,',') fart))) AND
 	CodUnitate = @CodUnitate AND [DataDoc]>=@data1 AND [DataDoc]<=@data2
	ORDER BY [DataDoc]
END


GO

UPDATE CONTURI SET Cont = LTRIM(RTRIM(Cont))
GO

UPDATE CONTURI2012 SET Cont = LTRIM(RTRIM(Cont))
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AmixRegistru' AND COLUMN_NAME = 'IDUnitateMasura')
BEGIN
	ALTER TABLE dbo.AmixRegistru ADD IDUnitateMasura smallint NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AmixRegistruBK' AND COLUMN_NAME = 'IDUnitateMasura')
BEGIN
	ALTER TABLE dbo.AmixRegistruBK ADD IDUnitateMasura smallint NULL
END
GO

IF NOT EXISTS (SELECT * FROM [UnitatiMasura] WHERE [Denumire] = 'METRU PATRAT')
BEGIN
INSERT INTO [UnitatiMasura]
           ([Denumire]
           ,[Compusa])
     VALUES
           ('METRU PATRAT',0)
END
GO

IF NOT EXISTS (SELECT * FROM [UnitatiMasura] WHERE [Denumire] = 'METRU LINIAR')
BEGIN
INSERT INTO [UnitatiMasura]
           ([Denumire]
           ,[Compusa])
     VALUES
           ('METRU LINIAR',0)
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IsContIn]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[IsContIn]
GO

CREATE FUNCTION [dbo].[IsContIn] (@Cont TipCont, @Multime varchar(2000))  
RETURNS int AS  
BEGIN 
DECLARE @ret int
SET @ret = CHARINDEX(LTRIM(RTRIM(@Cont)), @Multime)
return @ret
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IsContInclus]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[IsContInclus]
GO

CREATE FUNCTION [dbo].[IsContInclus] (@SursaParam TipCont, @DestinatieParam TipCont, @TerminalSursa bit)  
RETURNS bit AS  
BEGIN 
	DECLARE @inclus bit
	DECLARE @terminal bit
	DECLARE @Sursa TipCont
	DECLARE @Destinatie TipCont
	
	SET @Sursa = LTRIM(RTRIM(@SursaParam))
	SET @Destinatie = LTRIM(RTRIM(@destinatieParam))
	
	SET @terminal = 1
	SET @inclus = 0
	-- daca sunt egale e ok
	IF (@Destinatie = @Sursa)
		RETURN 1
	IF (substring(@Destinatie,1,len(@Sursa))=@Sursa) AND (@TerminalSursa=0)
		SET @inclus = 1
		
	IF LEN(@Destinatie) > LEN(@Sursa)
	BEGIN
		DECLARE @pos2 int
		SET @pos2 = CHARINDEX('.',@Sursa) 
		IF  @pos2<>0
		BEGIN		
			DECLARE @ch  varchar(1)
			SET @ch = substring(@Destinatie,LEN(@Sursa)+1,1)  
			IF @ch<>'.'
				SET @terminal = 0
		END
		
	END
	IF (@inclus=1) AND (@terminal=1)
		RETURN  1
	RETURN 0
END

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IsContInRetValoare]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[IsContInRetValoare]
GO

CREATE FUNCTION [dbo].[IsContInRetValoare] (@Cont TipCont, @Multime varchar(2000),@valoare DECIMAL(20,2))  
RETURNS DECIMAL(20,2) AS  
BEGIN 
DECLARE @ret int
SET @ret = CHARINDEX(LTRIM(RTRIM(@Cont)), @Multime)
IF @ret=0
	return 0
return @valoare
END


GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportPlati]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportPlati]
GO


CREATE PROCEDURE [dbo].[fares_FiltreazaRaportPlati] 
    @filtruPart varchar(8000),
	@filtruDocPlata varchar(8000),
	@data1 datetime,
	@data2 datetime,
	@numaiAvansuri bit,
	@documenteCLB smallint,
	@perioadaFactura bit,
	@data1p datetime,
	@data2p datetime,	
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

  SELECT * FROM [fares_Plati] WHERE 
    (LEN(LTRIM(RTRIM(@filtruDocPlata)))=0 OR (IDTipPlata IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruDocPlata,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
 	CodUnitate = @CodUnitate AND [Data]>=@data1 AND [Data]<=@data2 AND
 	(@numaiAvansuri=0 OR (@numaiAvansuri=1 AND [NrDoc] is NULL)) AND
 	((@documenteCLB=0 AND [TipOperatiune]='I') OR (@documenteCLB=1 AND [TipOperatiune]='O')) AND
 	(@perioadaFactura=0 OR (@perioadaFactura=1 AND [DataDoc]>=@data1p AND [DataDoc]<=@data2p))
	ORDER BY [DataDoc]
END

GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'UnitatiMasura' AND COLUMN_NAME = 'Prescurtare')
BEGIN
	ALTER TABLE dbo.UnitatiMasura ADD Prescurtare varchar(5) NOT NULL DEFAULT ''
END
GO



DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='F9B96690-0736-4F91-BC2C-F434651A1AFF' AND [HandlerName]='UnitatiMasura'
IF @Cate= 0 
begin
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(2209,'F9B96690-0736-4F91-BC2C-F434651A1AFF','Unitati de masura',2006,18,'UnitatiMasura',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF	
end 
go

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetFinalNumber]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[GetFinalNumber]
GO


CREATE FUNCTION [dbo].[GetFinalNumber]
(
	@Numar varchar(50)
)
RETURNS varchar(50)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @ResultVar varchar(50)
	SET @ResultVar = ''
	DECLARE @i int
	SET @i=LEN(@Numar)
	WHILE @i > 0
	BEGIN 
		if SUBSTRING(@numar,@i,1) <= '9' AND SUBSTRING(@numar,@i,1) >= '0'
			SET @i = @i - 1
		else
			break
	END 
	IF @i < LEN (@numar)
		SET @ResultVar = SUBSTRING(@numar,@i+1, LEN(@numar)-@i+1)
	
	-- Return the result of the function
	RETURN @ResultVar

END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetFinalNumberAntet]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[GetFinalNumberAntet]
GO


CREATE FUNCTION [dbo].[GetFinalNumberAntet]
(
	@Numar varchar(50)
)
RETURNS varchar(50)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @ResultVar varchar(50)
	SET @ResultVar = ''
	DECLARE @i int
	SET @i=LEN(@Numar)
	WHILE @i > 0
	BEGIN 
		if SUBSTRING(@numar,@i,1) <= '9' AND SUBSTRING(@numar,@i,1) >= '0'
			SET @i = @i - 1
		else
			break
	END 
	IF @i > 0
		SET @ResultVar = SUBSTRING(@numar,1,@i)
	
	-- Return the result of the function
	RETURN @ResultVar

END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[amix_ActSeriiNumerice]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[amix_ActSeriiNumerice]
GO

CREATE PROCEDURE [dbo].[amix_ActSeriiNumerice] 
	-- Add the parameters for the stored procedure here
	@IDSerie varchar(20),@CodUnitate smallint
AS
BEGIN
	SET NOCOUNT ON;
	UPDATE [SeriiNumerice] SET UltimulNrFolosit = dbo.GetFinalNumber((SELECT MAX(NrInventar) FROM [AmixRegistru] WHERE [CodUnitate]=@CodUnitate))+1,
		[UltimaDataFolosit]  = GETDATE(),
		Serie = SUBSTRING(dbo.GetFinalNumberAntet((SELECT MAX(NrInventar) FROM [AmixRegistru] WHERE [CodUnitate]=@CodUnitate)),1,10)
	 
	WHERE [CodUnitate]=@CodUnitate AND [IdSerie]=@IdSerie		
END

GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AmixRegistruBK' AND COLUMN_NAME = 'Luna')
BEGIN
	ALTER TABLE dbo.AmixRegistruBK ADD Luna smallint NOT NULL DEFAULT 0,
	An smallint NOT NULL DEFAULT 0

	ALTER TABLE dbo.AmixRegistruBK DROP CONSTRAINT IX_RegistruAmixBK

	ALTER TABLE dbo.AmixRegistruBK ADD CONSTRAINT
		IX_RegistruAmixBK UNIQUE NONCLUSTERED 
		(
		NrInventar,
		Luna,
		An
		)
END
GO





IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[AmixFisaMijlocFixView]'))
DROP VIEW [dbo].[AmixFisaMijlocFixView]
GO

CREATE VIEW [dbo].[AmixFisaMijlocFixView]
AS
SELECT     IDMijlocFix, NrInventar, NumarDoc, MONTH(DataDoc) AS Luna, YEAR(DataDoc) AS An, 
                      CASE WHEN IDTipDocument = 2 THEN 'INTRARE MIJLOC FIX' WHEN IDTipDocument = 3 THEN 'IESIRE MIJLOC FIX' WHEN IDTipDocument = 4 THEN 'TRANSFER INTERN' WHEN IDTipDocument = 5 THEN
                       'CONSERVARE' WHEN IDTipDocument = 6 THEN 'REACTIVARE' WHEN IDTipDocument = 7 THEN 'MODIFICARE VALOARE' WHEN IDTipDocument = 8 THEN 'MODERNIZARE ' ELSE 'ALT DOCUMENT' END
                       AS Miscare, DataDoc, CASE WHEN IDTipDocument = 2 THEN ValoareInventar WHEN IDTipDocument = 3 THEN 0 WHEN IDTipDocument = 8 AND 
                      ValoareSuplimentara > 0 THEN ValoareSuplimentara ELSE 0 END AS Debit, 
                      CASE WHEN IDTipDocument = 2 THEN 0 WHEN IDTipDocument = 3 THEN ValoareInventar - ValoareAmortizata WHEN IDTipDocument = 8 AND 
                      ValoareSuplimentara < 0 THEN - ValoareSuplimentara ELSE 0 END AS Credit
FROM         dbo.AmixDocumente

GO





IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[exbug_GenRegistrulOrdonantari]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[exbug_GenRegistrulOrdonantari]
GO

CREATE PROCEDURE [dbo].[exbug_GenRegistrulOrdonantari]
	@delaData datetime, 
	@panalaData datetime,
	@filtruArt varchar(8000),
	@delaNr decimal(18,0),
	@panalaNr decimal(18,0),
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
	SELECT  NrDoc, DataDoc, ValoareLei, Scop, DocJust, ArtAl, CodUnitate
	FROM    dbo.Ordonantari
	WHERE (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (ArtAl IN (SELECT fart.value FROM dbo.SplitParameters(@filtruArt,',') fart))) AND
	(@delaNr=-1 OR NrDoc >= @delaNr) AND
	(@panalaNr=-1 OR NrDoc <= @panalaNr) AND
	DataDoc>=@delaData AND DataDoc <=@panalaData
	AND CodUnitate = @CodUnitate
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaListaFisaMagazie]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaListaFisaMagazie]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaListaFisaMagazie] 
	-- Add the parameters for the stored procedure here
	@filtruArt varchar(8000),
	@laData datetime,
	@CodUnitate smallint
AS
BEGIN
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    SELECT * FROM
    (
    SELECT  td.Denumire+'('+td.TipOperatie + ')' Denumire, art.IDArticol,COALESCE(docDetSursa.ValoareUnitara,docDet.ValoareUnitara) ValoareUnitara,doc.IDDocument,
    art.Denumire DenumireArticol,um.Denumire DenumireUM,
    doc.DataDoc,doc.NrDoc,
    case when td.TipOperatie like '%I%' then docDet.Cantitate else 0 end Intrari,
    case when td.TipOperatie like '%O%' then 
    CASE WHEN fs.GestiuneCantitativa=1 THEN docDet.Cantitate ELSE COALESCE(docDetL.Cantitate,0) END 
    else 0 end Iesiri,

    coalesce((select SUM(s.StocInitial+s.StocPrecedent) FROM Stocuri s where s.IDArticol=docDet.IDArticol and s.Pret = COALESCE(docDetSursa.ValoareUnitara,docDet.ValoareUnitara)),0)
    + Coalesce((
	Select SUM(Cantitate) FROM 
	DocumenteDetaliu dd 
	JOIN Documente dct on dd.IDDocument=dct.IDDocument
    join TipDocument tipd ON dct.IDTipDocument = tipd.IDTipDocument
    where dd.IDArticol = docDet.IDArticol AND dd.ValoareUnitara = COALESCE(docDetSursa.ValoareUnitara,docDet.ValoareUnitara) and dct.DataCreation<=doc.DataCreation
    and tipd.TipOperatie like '%I%' and tipd.ModificaStoc=1 AND dct.AreDocGestStoc=1),
	0)
     - Coalesce((
	 Select CASE WHEN fs.GestiuneCantitativa=1 THEN SUM(dd.Cantitate) ELSE SUM(ddl.Cantitate) END Cantitate FROM 
	 DocumenteDetaliu dd 
	 JOIN Documente dct on dd.IDDocument=dct.IDDocument
     join TipDocument tipd ON dct.IDTipDocument = tipd.IDTipDocument
	 left outer join DocumenteDetaliuLink ddl ON dd.IDDocumentDetaliu = ddl.IDDocDetaliuDest
	 left outer join DocumenteDetaliu dds ON ddl.IDDocDetaliuSursa = dds.IDDocumentDetaliu
     where dd.IDArticol = docDet.IDArticol AND 
     ((fs.GestiuneCantitativa=1) OR dds.ValoareUnitara = COALESCE(docDetSursa.ValoareUnitara,docDet.ValoareUnitara)) and dct.DataCreation<=doc.DataCreation
     and tipd.TipOperatie like '%O%' and tipd.ModificaStoc=1 AND dct.AreDocGestStoc=1),0)
     stoc,
    docDet.ValoareTotala,docDet.ValoareTVA,Coalesce(doc.NrDocReceptie,'') NrDocReceptie,doc.DataDocReceptie,
    td.IDTipDocument,coalesce(art.Lungime,0) Lungime,coalesce(art.Latime,0) Latime,Coalesce(art.Grosime,0) Grosime,Coalesce(art.Greutate,0) Greutate,
	doc.DataCreation
    FROM [Articole] art
    LEFT OUTER JOIN [DocumenteDetaliu] docDet ON docDet.IDArticol = art.IDArticol
    JOIN [Documente] doc ON doc.IDDocument = docDet.IDDocument
    JOIN [TipDocument] td ON doc.IDTipDocument = td.IDTipDocument AND td.ModificaStoc=1
    JOIN UnitatiMasura um ON art.IDUnitateMasura = um.IDUnitateMasura
	LEFT OUTER JOIN [DocumenteDetaliuLink] docDetL ON docDetL.IDDocDetaliuDest = docDet.IDDocumentDetaliu AND docDetL.Cantitate<>0
	LEFT OUTER JOIN [DocumenteDetaliu] docDetSursa ON docDetL.IDDocDetaliuSursa = docDetSursa.IDDocumentDetaliu 
	JOIN [FaresSetup] fs ON art.CodUnitate = fs.CodUnitate

    WHERE 
    art.CodUnitate = @CodUnitate AND doc.AreDocGestStoc=1 AND
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (art.IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart)))
    )
    v
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetStocIesiriData]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[GetStocIesiriData]
GO

CREATE FUNCTION [dbo].[GetStocIesiriData]
(
	@IDArticol int,
	@Pret decimal(25,5),
	@LaData datetime,
	@GestCantitativa bit	
)
RETURNS decimal(25,5)
AS
BEGIN
	DECLARE @ResultVar decimal(25,5)
	IF @GestCantitativa=0
	BEGIN
		SELECT @ResultVar = COALESCE(SUM(ddl.Cantitate),0) FROM DocumenteDetaliu dd 
		JOIN Documente d ON d.IDDocument=dd.IDDocument
		JOIN DocumenteDetaliuLink  ddl ON ddl.IDDocDetaliuSursa = dd.IDDocumentDetaliu
		JOIN DocumenteDetaliu ddr ON ddl.IDDocDetaliuDest = ddr.IDDocumentDetaliu
		JOIN Documente dr ON ddr.IDDocument = dr.IDDocument
		WHERE dd.IDArticol=@IDArticol AND dd.ValoareUnitara=@Pret AND 
		(d.IDTipDocument = 0 OR d.IDTipDocument = 15) AND d.AreDocGestStoc=1 AND 
		(dr.IDTipDocument in (1,13,14)) AND dr.AreDocGestStoc=1 AND dr.DataDoc<=@LaData
	END
	ELSE
	BEGIN
		SELECT @ResultVar = COALESCE(SUM(dd.Cantitate),0) 
		FROM DocumenteDetaliu dd 
		JOIN Documente d ON d.IDDocument=dd.IDDocument 
		--AND d.AreDocGestStoc=1 
		AND d.DataDoc<=@LaData
		JOIN TipDocument td ON d.IDTipDocument = td.IDTipDocument AND td.TipOperatie LIKE '%O%'  AND td.ModificaStoc=1 
		WHERE dd.IDArticol=@IDArticol 
		 
	END
	RETURN @ResultVar

END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaListaStocuri]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaListaStocuri]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaListaStocuri] 
	@filtruArt varchar(8000),
	@filtruCat varchar(8000),
	@laData datetime,
	@StocuriZero bit,
	@Comparatie smallint,
	@ValoareStoc decimal(25,5),
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
    -- Insert statements for procedure here
    SELECT *,v.Stoc*v.ValoareUnitara ValoareTotala FROM
    (SELECT art.IDArticol,st.Pret ValoareUnitara,
    art.Denumire DenumireArticol,tca.Denumire DenumireCategorie, um.Denumire DenumireUM,
    st.StocInitial StocInitial,
    st.StocPrecedent StocPrecedent,
    dbo.GetStocIntrariData(st.IDArticol,st.Pret,@laData) Intrari ,
    dbo.GetStocIesiriData(st.IDArticol,st.Pret,@laData,fs.GestiuneCantitativa) Iesiri,
    st.StocInitial + st.StocPrecedent+dbo.GetStocIntrariData(st.IDArticol,st.Pret,@laData)- dbo.GetStocIesiriData(st.IDArticol,st.Pret,@laData,fs.GestiuneCantitativa) Stoc
    FROM [Articole] art
    JOIN [TipCategoriiArticole] tca ON art.IDCategorie = tca.IDCategorie
    LEFT OUTER JOIN [Stocuri] st ON st.IDArticol = art.IDArticol 
    JOIN UnitatiMasura um ON art.IDUnitateMasura = um.IDUnitateMasura
    JOIN FaresSetup fs ON fs.CodUnitate = art.CodUnitate
    WHERE 
    art.CodUnitate = @CodUnitate AND
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (art.IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruCat)))=0 OR (tca.IDCategorie IN (SELECT CAST(fart.value as smallint) FROM dbo.SplitParameters(@filtruCat,',') fart))) 
	) v
    WHERE 
    (@StocuriZero=1 OR Coalesce(Stoc,0)<>0) AND
    ((@Comparatie=0 AND Coalesce(Stoc,0) >@ValoareStoc) OR (@Comparatie=1 AND Coalesce(Stoc,0) >=@ValoareStoc) OR (@Comparatie=2 AND Coalesce(Stoc,0) =@ValoareStoc)
     OR (@Comparatie=3 AND Coalesce(Stoc,0) <=@ValoareStoc) OR (@Comparatie=4 AND Coalesce(Stoc,0) <@ValoareStoc) OR (@Comparatie=5 AND Coalesce(Stoc,0) <>@ValoareStoc))
     
END

GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'FolosesteCPV')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD FolosesteCPV bit NOT NULL DEFAULT 0
END
GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Import_AngajatiSalarizare]') AND type in (N'U'))
DROP TABLE [dbo].[Import_AngajatiSalarizare]
GO


CREATE TABLE [dbo].[Import_AngajatiSalarizare](
	[IDAngajatSalarizare] [int] NOT NULL,
	[Clasa] [smallint] NULL,
	[Gradatia] [varchar](20) NULL,
 CONSTRAINT [PK_Import_AngajatiSalarizare] PRIMARY KEY CLUSTERED 
(
	[IDAngajatSalarizare] ASC
)
)

GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'Marca')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD Marca int NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'NrContract')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD NrContract varchar(20) NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'DataContract')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD DataContract datetime NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'TipContract')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD TipContract int NULL
	ALTER TABLE dbo.AngajatiSalarizare ADD CONSTRAINT
		FK_AngajatiSalarizare_TipContracte FOREIGN KEY
		(TipContract) REFERENCES dbo.TipContracte (TipContract) ON UPDATE  NO ACTION 
		 ON DELETE  NO ACTION 
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'PerioadaDeterminata')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD PerioadaDeterminata bit NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'Observatii')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD Observatii varchar(250) NULL
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AngajatiSalarizare' AND COLUMN_NAME = 'DurataContract')
BEGIN
	ALTER TABLE dbo.AngajatiSalarizare ADD DurataContract float NULL
END
GO

IF NOT  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[Import_Persoane]'))
BEGIN
CREATE TABLE [dbo].[Import_Persoane](
	[IdPersoana] [int] IDENTITY(1,1) NOT NULL,
	[NumePrenume] [varchar](150) NOT NULL,
	[Nume_Anterior] [varchar](50) NULL,
	[Cnp] [decimal](13, 0) NOT NULL,
	[Sex] [smallint] NOT NULL DEFAULT ((0)),
	[DataNasterii] [datetime] NOT NULL,
	[IDLocNastere] [int] NOT NULL,
	[TipAI] [smallint] NOT NULL DEFAULT ((0)),
	[SeriaAI] [varchar](3) NOT NULL,
	[NumarAI] [varchar](15) NOT NULL,
	[DataElibAI] [datetime] NOT NULL,
	[EmitentAI] [varchar](100) NOT NULL,
	[NumeTata] [varchar](50) NULL,
	[NumeMama] [varchar](50) NULL,
	[StradaAdr] [varchar](100) NOT NULL,
	[IDLocalitateAdr] [int] NOT NULL,
	[NrAdr] [varchar](10) NOT NULL,
	[BlocAdr] [varchar](10) NOT NULL,
	[EtajAdr] [varchar](10) NULL,
	[ScaraAdr] [varchar](10) NULL,
	[ApartamentAdr] [varchar](10) NOT NULL,
	[GradInvaliditate] [smallint] NULL,
	[TelefonFix] [varchar](20) NULL,
	[TelefonMobil] [varchar](20) NOT NULL,
	[Observatii] [varchar](100) NULL,
	[NumarCM] [varchar](10) NOT NULL  DEFAULT ('') ,
	[SerieCM] [varchar](10) NOT NULL DEFAULT (''),
	[CodUnitate] [smallint] NOT NULL DEFAULT ((0)),
	[NrFileCM] [smallint] NOT NULL  DEFAULT ((0)),
	[NrCutieCM] [varchar](10) NOT NULL DEFAULT (''),
	[Marca] [varchar](20) NOT NULL DEFAULT ('FARA'),
	[TelefonInterior] [varchar](20) NULL,
	[IdCasaAsigSanatate] [smallint] NOT NULL DEFAULT ((0)),
	[IdTipStudii] [int] NOT NULL DEFAULT ((0)),
	[DataVechimeMunca] [datetime] NOT NULL DEFAULT (getdate()),
	[UserID] [uniqueidentifier] NULL,
	[PozCutieCM] [smallint] NOT NULL DEFAULT ((0)),
	[PlatesteCAS] [bit] NOT NULL DEFAULT ((1)),
	[PlatesteCASS] [bit] NOT NULL DEFAULT ((1)),
	[PlatesteSomaj] [bit] NOT NULL DEFAULT ((1)) ,
	[PlatesteImpozit] [bit] NOT NULL  DEFAULT ((1)) ,
	[AreDeducere] [bit] NOT NULL DEFAULT ((1)),
	[DataPlecarii] [datetime] NULL,
	[MotivIncetareContract] [varchar](250) NULL,
	[Operatie] [smallint] NOT NULL DEFAULT ((0)),
	[Selectat] [bit] NOT NULL DEFAULT ((1)),
 CONSTRAINT [PK_Import_Persoane] PRIMARY KEY CLUSTERED ([IdPersoana] ASC),
 CONSTRAINT [FK_IMPORT_PERSOANE_LOC_NASTERE] FOREIGN KEY([IDLocNastere])REFERENCES [dbo].[Localitati] ([IDLocalitate]),
 CONSTRAINT [FK_IMPORT_PERSOANE_LOCALITATI] FOREIGN KEY([IDLocalitateAdr]) REFERENCES [dbo].[Localitati] ([IDLocalitate]) ON UPDATE CASCADE ON DELETE CASCADE,
 CONSTRAINT [FK_IMPORT_PERSOANE_Localitati_Nastere] FOREIGN KEY([IDLocNastere]) REFERENCES [dbo].[Localitati] ([IDLocalitate]),
 CONSTRAINT [FK_IMPORT_PERSOANE_Unitati] FOREIGN KEY([CodUnitate]) REFERENCES [dbo].[Unitati] ([CodUnitate])
) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AmixRegistru' AND COLUMN_NAME = 'ContTransferForSuperior')
BEGIN
	ALTER TABLE dbo.AmixRegistru ADD ContTransferForSuperior dbo.TipCont NULL
	ALTER TABLE dbo.AmixRegistruBK ADD ContTransferForSuperior dbo.TipCont NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AmixRegistru' AND COLUMN_NAME = 'IDJurnal')
BEGIN
	ALTER TABLE dbo.AmixRegistru ADD IDJurnal int NULL
	ALTER TABLE dbo.AmixRegistruBK ADD IDJurnal int NULL

	ALTER TABLE dbo.AmixRegistru ADD CONSTRAINT
		FK_AmixRegistru_Jurnale FOREIGN KEY
		(IDJurnal) REFERENCES dbo.Jurnale (IDJurnal) ON UPDATE  NO ACTION 
		 ON DELETE  NO ACTION 

END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AmixRegistru' AND COLUMN_NAME = 'ValoareIntrataTransfer')
BEGIN
	ALTER TABLE dbo.AmixRegistru ADD ValoareIntrataTransfer decimal(25,2) NULL
	ALTER TABLE dbo.AmixRegistruBK ADD ValoareIntrataTransfer decimal(25,2) NULL
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[amix_DeschideLuna]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[amix_DeschideLuna]
GO


CREATE PROCEDURE [dbo].[amix_DeschideLuna] 
	-- Add the parameters for the stored procedure here
	@Luna smallint, 
	@An smallint,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
  
	--sterge mijloacele fixe introduse in luna curenta
	BEGIN TRAN		
		
		UPDATE [AmixRegistru]
		SET    [NrInventar] = arh.NrInventar 
			  ,[Denumire] = arh.Denumire
			  ,[ContAmortizare] = arh.ContAmortizare
			  ,[StocFaptic] = arh.StocFaptic
			  ,[IDClasificare] = arh.IDClasificare
			  ,[DataIntrare] = arh.DataIntrare
			  ,[DataIesire] = arh.DataIesire
			  ,[IDDepartament] = arh.IDDepartament
			  ,[IDStare] = arh.IDStare
			  ,[ContImobilizare] = arh.ContImobilizare
			  ,[ContCheltuiala] = arh.ContCheltuiala
			  ,[DurataAmortizare] = arh.DurataAmortizare
			  ,[RegimAmortizare] = arh.RegimAmortizare
			  ,[ValoareInventar] = arh.ValoareInventar
			  ,[PunereInFunctiune] = arh.PunereInFunctiune
			  ,[Compus] = arh.Compus
			  ,[Blocat] = arh.Blocat
			  ,[IDGestionar] = arh.IDGestionar
			  ,[ContTransfer] = arh.ContTransfer
			  ,[ValoareAmortizata] = arh.ValoareAmortizata
			  ,[LuniAmortizate] = arh.LuniAmortizate
			  ,[AmortizareLuna] = arh.AmortizareLuna
			  ,[AmortizareAn] = arh.AmortizareAn
			  ,[InFolosinta] = arh.InFolosinta
			  ,[CantitateOI] = arh.CantitateOI
			  ,[Categorie] = arh.Categorie
			  ,[IDUnitateMasura] = arh.IDUnitateMasura
			  ,[ContTransferForSuperior] = arh.ContTransferForSuperior
			  ,[IDJurnal]=arh.IDJurnal
			  ,[ValoareIntrataTransfer]=arh.ValoareIntrataTransfer
			   FROM [AmixRegistruBK] arh  
			WHERE  [AmixRegistru].IDMijlocFix = arh.IDMijlocFix AND arh.Luna = @Luna AND arh.An=@An
		
		IF @@ERROR <>0 GOTO Eroare

		UPDATE [AmixSetup] SET [LunaCurenta]= @Luna,[AnulCurent]=@An
		WHERE [CodUnitate]=@CodUnitate
		IF @@ERROR <>0 GOTO Eroare 
		
		
	    EXEC [amix_InchideLuna2] @Luna,@An,@CodUnitate,0,0;

	COMMIT

	---inchidere luna

	GOTO Gata
	DUBLURI:
		RAISERROR ('Exista mijloace fixe cu acelasi numar de inventar',16,-1)
		GOTO Gata

	EROARE:
		ROLLBACK
		RAISERROR ('Eroare la prelucrarea datelor',16,-1)
		GOTO Gata

		GATA:
END

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[resuma_ImportPersSal]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[resuma_ImportPersSal]
GO

CREATE PROCEDURE [dbo].[resuma_ImportPersSal]
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DELETE FROM [Import_Persoane]
    INSERT INTO [Import_Persoane]
           ([NumePrenume]
           ,[Nume_Anterior]
           ,[Cnp]
           ,[Sex]
           ,[DataNasterii]
           ,[IDLocNastere]
           ,[TipAI]
           ,[SeriaAI]
           ,[NumarAI]
           ,[DataElibAI]
           ,[EmitentAI]
           ,[NumeTata]
           ,[NumeMama]
           ,[StradaAdr]
           ,[IDLocalitateAdr]
           ,[NrAdr]
           ,[BlocAdr]
           ,[EtajAdr]
           ,[ScaraAdr]
           ,[ApartamentAdr]
           ,[GradInvaliditate]
           ,[TelefonFix]
           ,[TelefonMobil]
           ,[Observatii]
           ,[NumarCM]
           ,[SerieCM]
           ,[CodUnitate]
           ,[NrFileCM]
           ,[NrCutieCM]
           ,[Marca]
           ,[TelefonInterior]
           ,[IdCasaAsigSanatate]
           ,[IdTipStudii]
           ,[DataVechimeMunca]
           ,[PozCutieCM]
           ,[PlatesteCAS]
           ,[PlatesteCASS]
           ,[PlatesteSomaj]
           ,[PlatesteImpozit]
           ,[AreDeducere]
           ,[DataPlecarii]
           ,[MotivIncetareContract]
           ,[Operatie]
           ,[Selectat])
     SELECT  LTRIM(RTRIM([Nume])) + ' ' + LTRIM(RTRIM([Prenume]))  as Nume_Prenume,
     LTRIM(RTRIM(Anterior)),pp.[Cnp],pp.Sex,[DataNast],
     COALESCE(
     (SELECT TOP 1 IDLocalitate FROM Localitati WHERE (Nume like '%' + LN_Loc + '%') OR (Nume like '%' + LN_Sat + '%')),0) IDLocalitate,
     AI_Tip, AI_Ser, AI_Nr,COALESCE(AI_DatEl,GETDATE()) [DataElibAI] ,AI_Elib,
     '' AS NumeMama, '' AS NumeTata, Adr_Str,
     COALESCE((SELECT TOP 1 IDLocalitate FROM Localitati WHERE (Nume like '%' + Adr_Loc + '%') OR (Nume like '%' + Adr_Sat + '%')),0) IDLocalitateAdr,
     Adr_Nr,Adr_Bloc,Adr_Et, Adr_Sc, Adr_Ap,
     Handic as GradInvaliditate, Adr_Tel,Adr_Tel, Mentiuni AS Observatii,
     CMNr,CMSer,@CodUnitate,0 AS NrFile, 0 AS NrCutie,pp.Marca,  '' as Telefoninterior, CodCasaSan,
     CodStudii,COALESCE(COALESCE(DataPrAnga,DataUnit),GETDATE()) as [DataVechimeMunca], 0 AS PozCutieCM,  
     1 AS PlatesteCAS,ScutAsSA=1, ScutSomA,ScutImpA,0 as arededucere,DataPlec,
     artPlec + '-' + litPlec as MotivIncetare,0,1 AS Selectat  
     FROM PersSal.dbo.pPerson pp LEFT OUTER JOIN [Persoane] pr ON pp.CNP = pr.Cnp AND pr.CodUnitate = @CodUnitate
     JOIN PersSal.dbo.pPersSal pe ON pp.Marca=pe.Marca
     WHERE  pr.IdPersoana is null
	
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CalcDisponibilPAC]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CalcDisponibilPAC]
GO



CREATE PROCEDURE [dbo].[CalcDisponibilPAC]
	@CodUnitate smallint,
	@IDPAC int,
	@Data datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	UPDATE [PropunereAngajareCheltuialaDetaliu] SET [CredBugAprob]= 
	(SELECT coalesce(SUM(ValoareLei),0) FROM [Rulaje] r JOIN ExBugSetup es ON es.CodUnitate=r.CodUnitate
	 WHERE (IDDocument IN 
	 (SELECT IDDocument FROM RulajeDoc rd  WHERE
		IDJurnal = [PropunereAngajareCheltuialaDetaliu].[IDJurnal] AND [CodUnitate]=@CodUnitate AND DataDoc<=@Data)) AND ContDebit= LTRIM(RTRIM(es.ContBA)) + '.'+[PropunereAngajareCheltuialaDetaliu].[ArtAl])
	  -(SELECT coalesce(SUM(ValoareLei),0) FROM [Rulaje] r JOIN ExBugSetup es ON es.CodUnitate=r.CodUnitate WHERE (IDDocument IN 
	  (SELECT IDDocument FROM RulajeDoc WHERE
		IDJurnal = [PropunereAngajareCheltuialaDetaliu].[IDJurnal] AND [CodUnitate]=@CodUnitate AND DataDoc<=@Data)) AND ContCredit= LTRIM(RTRIM(es.ContBA)) + '.'+[PropunereAngajareCheltuialaDetaliu].[ArtAl])
		WHERE [IDPac]=@IDPAC

	UPDATE [PropunereAngajareCheltuialaDetaliu] SET [CredBugAngaj]= (SELECT coalesce(SUM(ValoareLei),0) FROM [Rulaje] 
	r JOIN ExBugSetup es ON es.CodUnitate=r.CodUnitate WHERE (IDDocument IN (SELECT IDDocument FROM RulajeDoc WHERE
		IDJurnal = [PropunereAngajareCheltuialaDetaliu].[IDJurnal] AND [CodUnitate]=@CodUnitate  AND DataDoc<@Data)) AND ContDebit= LTRIM(RTRIM(es.ContAL)) +'.'+[PropunereAngajareCheltuialaDetaliu].[ArtAl])
		-(SELECT coalesce(SUM(ValoareLei),0) FROM [Rulaje] r JOIN ExBugSetup es ON es.CodUnitate=r.CodUnitate WHERE (IDDocument IN (SELECT IDDocument FROM RulajeDoc WHERE
		IDJurnal = [PropunereAngajareCheltuialaDetaliu].[IDJurnal] AND [CodUnitate]=@CodUnitate  AND DataDoc<@Data)) AND ContCredit= LTRIM(RTRIM(es.ContAL)) + '.'+[PropunereAngajareCheltuialaDetaliu].[ArtAl]) 
		--+(SELECT COALESCE(sum(Suma),0) FROM [PropunereAngajareCheltuialaDetaliu] a JOIN [PropunereAngajareCheltuiala] b ON a.IDPac=b.IDPAC  WHERE a.[IDPACDetaliu] < [PropunereAngajareCheltuialaDetaliu].[IDPACDetaliu] AND a.ArtAl = [PropunereAngajareCheltuialaDetaliu].[ArtAl]
		--AND b.Data < @Data)
		WHERE [IDPac]=@IDPAC
		
		
	UPDATE [PropunereAngajareCheltuialaDetaliu] SET [Clasif]=LTRIM(RTRIM(j.[Codificare]))+'.' +dbo.GetTitlu([ArtAl])+'.' + LTRIM(RTRIM([ArtAl]))  FROM [Jurnale] j WHERE j.[IDJurnal] = [PropunereAngajareCheltuialaDetaliu] .[IDJurnal] AND [IDPAC] =@IDPAC
END

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[exbug_GenereazaPACsiAB]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[exbug_GenereazaPACsiAB]
GO



CREATE PROCEDURE [dbo].[exbug_GenereazaPACsiAB]
	-- Add the parameters for the stored procedure here
	@IDDocument bigint,
	@CodUnitate smallint,
	@IDPAC int OUT,
	@IDAB int OUT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @IDResponsabil int
	SET @IDResponsabil = 0
	
	SELECT TOP 1 @IDResponsabil = [IDResponsabil] FROM ResponsabilVizaCFP WHERE [CodUnitate] = @CodUnitate
	IF @IDResponsabil = 0
		GOTO Eroare

	--Propunere angajare cheltuiala
    INSERT INTO [PropunereAngajareCheltuiala]
           ([Numar]
           ,[Data]
           ,[Compartiment]
           ,[Scopul]
           ,[Beneficiarul]
           ,[CodUnitate]
           ,[SumaTotala]
           ,[VizatCFP]
           ,[MotivRefuz]
           ,[IDResponsabil]
           ,[DataVizaCFP]
           ,[NrRegCFP]
           ,[OrdonatorCredite])
     SELECT CAST(NumarDoc as varchar(20)) [Numar],
		[DataDoc],
		[CompartimentSpecialitate],
		COALESCE([Observatii],''),
		[Linia1Stanga],
		rd.[CodUnitate],
		ValoareLei,
		1,'',@IDResponsabil,GETDATE(),'',[OrdonatorCredite]
      FROM [RulajeDoc] rd JOIN ExBugSetup ebs ON rd.CodUnitate = ebs.CodUnitate
       JOIN BalconSetup bcs ON bcs.CodUnitate = rd.CodUnitate
			 WHERE [IDDocument]=@IDDocument 
           
	SET @IDPAC= SCOPE_IDENTITY()

	INSERT INTO [PropunereAngajareCheltuialaDetaliu]
           ([IDPac]
           ,[IDJurnal]
           ,[ArtAl]
           ,[Suma]
           ,[CredBugAprob]
           ,[CredBugAngaj]
           ,[Clasif])
     SELECT @IDPAC,sd.IDJurnal,REPLACE(ContDebit, ContAB+'.','') ArtAl ,
     CASE WHEN rl.ContDebit like ContAB +'%' THEN rl.valoareLei ELSE  -rl.valoareLei END,0,0,'' FROM 
     Rulaje rl JOIN [RulajeDoc] sd ON sd.IDDocument=rl.IDDocument
     JOIN ExBugSetup ebs ON ebs.CodUnitate = rl.CodUnitate
		WHERE rl.[IDDocument]=@IDDocument
		AND ((rl.ContDebit like ContAB +'%') OR (rl.ContCredit like ContAB +'%'))

	

	--Angajament bugetar
    INSERT INTO [AngajamentBugetar]
           ([Numar]
           ,[Data]
           ,[Compartiment]
           ,[Scopul]
           ,[Beneficiarul]
           ,[CodUnitate]
           ,[SumaTotala]
           ,[VizatCFP]
           ,[MotivRefuz]
           ,[IDResponsabil]
           ,[DataVizaCFP]
           ,[NrRegCFP]
           ,[OrdonatorCredite],
           [TipAngajament])
     SELECT CAST(NumarDoc as varchar(20)) [Numar],
		[DataDoc],
		[CompartimentSpecialitate],
		COALESCE([Observatii],''),
		[Linia1Stanga],
		rd.[CodUnitate],
		[ValoareLei],
		1,'',@IDResponsabil,GETDATE(),'',[OrdonatorCredite],0
      FROM [RulajeDoc] rd JOIN ExBugSetup ebs ON rd.CodUnitate = ebs.CodUnitate
       JOIN BalconSetup bcs ON bcs.CodUnitate = rd.CodUnitate
			 WHERE [IDDocument]=@IDDocument 
           
	SET @IDAB= SCOPE_IDENTITY()

	INSERT INTO [AngajamentBugetarDetaliu]
           ([IDAB]
           ,[IDJurnal]
           ,[ArtAl]
           ,[Suma]
           ,[Clasif])
     SELECT @IDAB,sd.IDJurnal,REPLACE(ContDebit, ContAB+'.','') ArtAl ,
     rl.valoareLei,'' FROM 
     Rulaje rl JOIN [RulajeDoc] sd ON sd.IDDocument=rl.IDDocument
     JOIN ExBugSetup ebs ON ebs.CodUnitate = rl.CodUnitate
		WHERE rl.[IDDocument]=@IDDocument
		AND ((rl.ContDebit like ContAB +'%') OR (rl.ContCredit like ContAB +'%'))

		
		         
	GOTO Gata
Eroare:
	 RAISERROR ('Nu a fost definit responsabilul pentru viza CFP1',16,-1)
Gata:

END

GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ExBugSetup' AND COLUMN_NAME = 'StergePACABGenerat')
BEGIN
	ALTER TABLE ExBugSetup ADD StergePACABGenerat bit NOT NULL DEFAULT 1
END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[AmixViewAll]'))
DROP VIEW [dbo].[AmixViewAll]
GO


CREATE VIEW [dbo].[AmixViewAll]
AS
SELECT     dbo.AmixRegistru.NrInventar, dbo.AmixRegistru.Denumire, dbo.AmixRegistru.ContAmortizare, dbo.AmixCatalog.Cod, dbo.AmixRegistru.DataIntrare, dbo.AmixRegistru.DataIesire, 
                      dbo.AmixRegistru.CodUnitate, dbo.Departamente.Nume, dbo.AmixRegistru.ContImobilizare, dbo.AmixRegistru.ContCheltuiala, dbo.AmixRegistru.DurataAmortizare, 
                      dbo.AmixRegistru.RegimAmortizare, dbo.AmixRegistru.ValoareInventar, dbo.AmixRegistru.ValoareAmortizata, 
                      dbo.AmixRegistru.ValoareInventar - dbo.AmixRegistru.ValoareAmortizata AS ValoareRamasa, 0 AS AmortizareLuna, dbo.AmixRegistru.DurataAmortizare AS DurataNormata, 
                      dbo.AmixRegistru.LuniAmortizate, dbo.AmixTipStare.Denumire AS Stare, 0 AS Luna, 0 AS An, dbo.AmixRegistru.Blocat, dbo.AmixRegistru.Compus, 0 AS AmortizareBlocata, 
                      dbo.AmixRegistru.IDMijlocFix, dbo.AmixGestionari.Nume AS Gestionar, dbo.AmixRegistru.IDStare, dbo.AmixRegistru.StocFaptic, dbo.AmixRegistru.Categorie, dbo.AmixCatalog.Grupa, 
                      dbo.AmixRegistru.ContTransferForSuperior, dbo.AmixRegistru.ValoareIntrataTransfer, dbo.Jurnale.Codificare
FROM         dbo.AmixRegistru LEFT OUTER JOIN
                      dbo.AmixCatalog ON dbo.AmixRegistru.IDClasificare = dbo.AmixCatalog.IDClasificare INNER JOIN
                      dbo.Departamente ON dbo.AmixRegistru.IDDepartament = dbo.Departamente.IDDepartament INNER JOIN
                      dbo.AmixTipStare ON dbo.AmixRegistru.IDStare = dbo.AmixTipStare.IDStare INNER JOIN
                      dbo.AmixGestionari ON dbo.AmixRegistru.IDGestionar = dbo.AmixGestionari.IDGestionar LEFT OUTER JOIN
                      dbo.Jurnale ON dbo.AmixRegistru.IDJurnal = dbo.Jurnale.IDJurnal

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_GenereazaDocumentePentruPlata]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_GenereazaDocumentePentruPlata]
GO

CREATE PROCEDURE [dbo].[fares_GenereazaDocumentePentruPlata]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint, 
	@IDPartener bigint,
	@TipOperatiune varchar(10),
	@IDDocumentPlata int,
	@An varchar(4)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	
    SELECT doc.IDDocument,NrDoc,DataDoc,NrDoc + '/' +CONVERT(varchar(20),DataDoc,104) NrDataDoc ,IDPartener,CodUnitate,Total,TotalValoareTVA,
	Coalesce(Achitat,0) Achitat,COALESCE(AchitatTVA,0) AchitatTVA, 
	Total - Coalesce(Achitat,0) RestPlata,TotalValoareTVA -Coalesce(AchitatTVA,0) RestPlataTVA,  DataScadenta
	FROM [Documente] doc 
	JOIN TipDocument tdoc ON doc.IDTipDocument = tdoc.IDTipDocument and tDoc.SePlateste=1
	LEFT OUTER JOIN
	(SELECT IDDocument, SUM(Valoare) Achitat,SUM(ValoareTVA) AchitatTVA 
	   FROM [DocumentePlataDetaliu] dpd
	   WHERE
	   (@IDDocumentPlata < 0 OR (dpd.IDDocumentPlata <> @IDDocumentPlata)) 
	   GROUP BY IDDocument) pldoc ON pldoc.IDDocument=doc.IDDocument
	WHERE CodUnitate=@CodUnitate  AND IDPartener = @IDPartener AND
	tdoc.TipOperatie like '%'+@TipOperatiune+'%'
	UNION
	SELECT NULL, '',GETDATE(),'AVANS',@IDPartener,@CodUnitate,0,0,0,0,0,0,GETDATE() 
	FROM FaresSetup WHERE CodUnitate=@CodUnitate 
	ORDER BY DataDoc DESC
	
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportDocumenteTVA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportDocumenteTVA]
GO

CREATE PROCEDURE [dbo].[fares_FiltreazaRaportDocumenteTVA] 
    @filtruPart varchar(8000),
	@filtruArt varchar(8000),
	@filtruTipDoc varchar(2000),
	@data1 datetime,
	@data2 datetime,
	@DefalcatTVA bit,
	@receptie bit,
	@CodUnitate smallint,
	@dataReceptie1 datetime,
	@dataReceptie2 datetime
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	SELECT * FROM [fares_DocumenteTVADimensiuni] WHERE 
    (LEN(LTRIM(RTRIM(@filtruArt)))=0 OR (IDArticol IN (SELECT fart.value FROM dbo.SplitIntParameters(@filtruArt,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND
    (LEN(LTRIM(RTRIM(@filtruTipDoc)))=0 OR (IDTipDocument IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruTipDoc,',') fart))) AND
    (@receptie=0 OR (@receptie=1 AND [TipOperatie] LIKE '%I%' AND IDTipDocument=0)) AND
    ([ValoareTotalaCuAdaos24]<>0 OR [ValoareTotalaCuAdaos9]<>0) AND 
	CodUnitate = @CodUnitate AND [DataDoc]>=@data1 AND [DataDoc]<=@data2
	AND [DataDocReceptie]>=@dataReceptie1 AND [DataDocReceptie]<=@dataReceptie2
	ORDER BY [DataDoc]

END

GO



IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AmixRegistru' AND COLUMN_NAME = 'CantitateOI' AND DATA_TYPE ='int')
BEGIN
	ALTER TABLE AmixRegistru ADD CantitateOI decimal(18,2) NOT NULL DEFAULT 0
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AmixRegistruBK' AND COLUMN_NAME = 'CantitateOI' AND DATA_TYPE ='int')
BEGIN
	ALTER TABLE AmixRegistruBK ADD CantitateOI decimal(18,2) NOT NULL DEFAULT 0
END
GO




IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AmixDocumente' AND COLUMN_NAME = 'CantitateOI' AND DATA_TYPE ='int')
BEGIN
	ALTER TABLE AmixDocumente ADD CantitateOI decimal(18,2) NOT NULL DEFAULT 0
END
GO

 UPDATE [ParamListe] SET ValoareImplicita='Generala|ITCSF|ITSCF|'  WHERE  Cod='STL' AND  IDLista=1 
 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetBalanta]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetBalanta]
GO



CREATE PROCEDURE [dbo].[GetBalanta] 
	-- Add the parameters for the stored procedure here
	@pDtDataStartUI datetime,
	@pDtDataEndUI datetime,
	@pJurnal int,
	@pCategorie int,
	@pStrContStart TipCont,
	@pStrContEnd TipCont,
	@pCfm bit,
	@pAnalitica bit,
	@pCfmRulaje bit,
	@pTerminal bit,
	@An smallint,
	@Tgc bit
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
DECLARE @CodUnitate smallint
DECLARE @cmd varchar(5000)
DECLARE @strCodUnitate varchar(20)
DECLARE @DtDataStartUI varchar(20)
DECLARE @DtDataEndUI varchar(20)
DECLARE @strCategorie varchar(100)
DECLARE @strAn varchar(10)

SET @CodUnitate=0
SELECT @CodUnitate=CAST(Valoare AS smallint) FROM [SetariLocale] WHERE [CodSetare]='UCRT' AND [xUser]=suser_sname() AND [xHost]=host_name()
SET @strCodUnitate = cast(@CodUnitate AS varchar(20))

DECLARE @ConturiTGC AS varchar(2000)
SET @ConturiTGC = ','
SELECT @ConturiTGC=@ConturiTGC + Cont + ',' FROM ConturiSpeciale WHERE Tipuri like'%{TGC}%' AND [CodUnitate]=@CodUnitate

DECLARE @ConturiSS AS varchar(2000)
SET @ConturiSS = ','
SELECT @ConturiSS=@ConturiSS + Cont + ',' FROM ConturiSpeciale WHERE Tipuri like'%{CSS}%' AND [CodUnitate]=@CodUnitate



SET @DtDataStartUI = cast(YEAR(@pDtDataStartUI) as varchar(4)) + '-' +cast(MONTH(@pDtDataStartUI) as varchar(2)) + '-' + cast(DAY(@pDtDataStartUI) as varchar(2))
SET @DtDataEndUI = cast(YEAR(@pDtDataEndUI) as varchar(4)) + '-' +cast(MONTH(@pDtDataEndUI) as varchar(2)) + '-' + cast(DAY(@pDtDataEndUI) as varchar(2))

SET @strCategorie = LTRIM(RTRIM(cast(@pCategorie as varchar(10))))
SET @strAn = cast(@An as varchar(10))

IF @Tgc=1
	SET @strCategorie = @strCategorie + ',3'

SET @cmd = 'SELECT  Cont,ContParinte,Terminal,Denumire,Tip,Categorie,SortValue,DebInit [SoldInitDeb],CreInit [SoldInitCre], 
    DebPrecCalc [RulPrecDeb], CrePrecCalc [RulPrecCre], 
    DebCurent [RulCurentDeb], CreCurent [RulCurentCre],
	DebInit + DebPrecCalc+ COALESCE(DebCurent, 0) RulTotalDeb, CreInit +CrePrecCalc + COALESCE(CreCurent, 0) RulTotalCre, 
	dbo.SoldDebit(Tip, DebInit + DebPrecCalc + COALESCE(DebCurent, 0), CreInit + CrePrecCalc + COALESCE(CreCurent, 0)) SoldTotalDeb, 
	dbo.SoldCredit(Tip, DebInit + DebPrecCalc + COALESCE(DebCurent, 0), CreInit + CrePrecCalc + COALESCE(CreCurent, 0)) SoldTotalCre
	FROM
	(SELECT c.Cont, C.Denumire,C.EsteAnalitic, C.Tip,C.Categorie,C.ContParinte,C.Terminal,C.SortValue, c.DebitInitial AS [DebInit], c.CreditInitial AS [CreInit], 
	sum(COALESCE(DebPrecCalc, 0)) DebPrecCalc,sum(COALESCE(CrePrecCalc, 0)) CrePrecCalc,  
	sum(COALESCE(DebCurent, 0)) DebCurent, sum(COALESCE(CreCurent, 0)) CreCurent
	FROM '
IF @Tgc=1
BEGIN
	DECLARE @cmdCont varchar(2000)
	SET @cmdCont =  
	'(SELECT a.[Cont],a.[CodUnitate],a.[Denumire],a.[Tip],a.[Terminal],a.[ContParinte],a.[EsteAnalitic],a.[Categorie],a.[SortValue],a.[DebitPrecedent],a.[CreditPrecedent],
	sum(b.DebitInitial) [DebitInitial] ,sum(b.creditInitial) [CreditInitial]
	FROM [Conturi] a JOIN [Conturi] b
	ON dbo.IsContInclus(a.cont,b.cont,a.Terminal)=1 and a.codunitate=b.codunitate
	where a.[CodUnitate]=' + @strCodUnitate +' and a.categorie=3 and b.ContParinte=''N/A''
	group by a.[Cont],a.[CodUnitate],a.[Denumire],a.[Tip],a.[Terminal],a.[ContParinte],a.[EsteAnalitic],a.[Categorie],a.[SortValue],a.[DebitPrecedent],a.[CreditPrecedent]
	UNION
	SELECT  a2.[Cont],a2.[CodUnitate],a2.[Denumire],a2.[Tip],a2.[Terminal],a2.[ContParinte],a2.[EsteAnalitic],a2.[Categorie],a2.[DebitPrecedent],a2.[CreditPrecedent],
	a2.[DebitInitial] ,a2.[CreditInitial] FROM [Conturi] a2
	WHERE a2.codunitate='+@strCodUnitate +' and a2.categorie=0 )'
	IF @An <> 0 
		SET @cmdCont = REPLACE(@cmdCont,'[Conturi]', '[Conturi' + @strAn + ']')
	
	SET @cmd = @cmd  + @cmdCont
END
ELSE
BEGIN
	IF @An <> 0 
		SET @cmd = @cmd  + '[Conturi' + @strAn + ']'
	ELSE
		SET @cmd = @cmd  + '[Conturi]'
END

SET @cmd = @cmd  + ' c
    LEFT OUTER JOIN 
	(SELECT sum(sumaDebitPrec) DebPrecCalc, sum(sumaCreditPrec) AS CrePrecCalc,
	   sum(sumaDebit) AS DebCurent, sum(sumaCredit) AS CreCurent, Cont, CodUnitate,IDJurnal FROM
			(SELECT 			    
				coalesce(SUM(CASE WHEN D.DataDoc<''' + @DtDataStartUI + ''' THEN F.ValoareLei ELSE 0 END),0) sumaDebitPrec,
				coalesce(SUM(CASE WHEN D.DataDoc>=''' + @DtDataStartUI +''' AND D.DataDoc<=''' + @DtDataEndUI +''' THEN F.ValoareLei ELSE 0 END),0) sumaDebit, 
				0.00 AS sumaCreditPrec, 0.00 AS sumaCredit, 
				F.ContDebit AS Cont,D.CodUnitate AS CodUnitate,D.IdJurnal AS Idjurnal
				FROM '
--[RulajeDoc]
IF @An <> 0 
	SET @cmd = @cmd  + '[RulajeDoc' + @strAn + ']'
ELSE
	SET @cmd = @cmd  + '[RulajeDoc]'

SET @cmd = @cmd  + ' D INNER JOIN '
--[Rulaje]
IF @An <> 0 
	SET @cmd = @cmd  + '[Rulaje' + @strAn + ']'
ELSE
	SET @cmd = @cmd  + '[Rulaje]'


SET @cmd = @cmd  + ' F ON D.[IDDocument] = F.[IDDocument] 
				WHERE  d.[CodUnitate] =' +  @strCodUnitate
			
IF 	@pJurnal<>-1	
	SET @cmd = @cmd + 	' AND D.IDJurnal= ' + cast(@pJurnal as varchar(10)) 
					
SET @cmd = @cmd  + ' GROUP BY F.ContDebit,D.CodUnitate,D.IDJurnal
			UNION
			SELECT 
				0.00 AS sumaDebitPrec, 0.00 AS sumaDebit,
				coalesce(SUM(CASE WHEN D.DataDoc < ''' + @DtDataStartUI+''' THEN F.ValoareLei ELSE 0 END),0) sumaCreditPrec,
				coalesce(SUM(CASE WHEN D.DataDoc >=''' + @DtDataStartUI+''' AND D.DataDoc<=''' + @DtDataEndUI +''' THEN F.ValoareLei ELSE 0 END),0) sumaCredit, 
                F.ContCredit AS Cont,D.CodUnitate  AS CodUnitate,D.IDJurnal AS Idjurnal
				FROM '
--[RulajeDoc]
IF @An <> 0 
	SET @cmd = @cmd  + '[RulajeDoc' + @strAn + ']'
ELSE
	SET @cmd = @cmd  + '[RulajeDoc]'

SET @cmd = @cmd  + ' D INNER JOIN '
--[Rulaje]
IF @An <> 0 
	SET @cmd = @cmd  + '[Rulaje' + @strAn + ']'
ELSE
	SET @cmd = @cmd  + '[Rulaje]'

SET @cmd = @cmd  + ' F ON D.[IDDocument] = F.[IDDocument] 
				WHERE d.[CodUnitate] = '+@strCodUnitate 
IF 	@pJurnal<>-1	
	SET @cmd = @cmd + 	' AND D.IDJurnal= ' + cast(@pJurnal as varchar(10)) 
			

SET @cmd = @cmd +  ' GROUP BY F.ContCredit,D.CodUnitate,D.IDJurnal) t1
	GROUP BY Cont,CodUnitate,IDJurnal
	) RUL 
	ON dbo.IsContInclus(c.cont,rul.cont,c.Terminal)=1 AND c.CodUnitate=rul.CodUnitate
	WHERE  c.[Cont]<>''N/A'' AND Categorie in ('+ @strCategorie + ') AND c.[CodUnitate] ='+ @strCodUnitate + '
	AND c.Cont >= '''+@pStrContStart + ''''
IF @pStrContEnd	<> ''
	SET @cmd = @cmd + ' AND c.Cont <='''+ @pStrContEnd +''''
	
SET @cmd = @cmd +  'GROUP BY  c.Cont, C.Denumire,  C.Tip, C.Categorie, C.ContParinte,C.Terminal,C.SortValue,c.CreditInitial, CreditPrecedent,  c.DebitInitial, DebitPrecedent,C.EsteAnalitic
	) [balanta] '

DECLARE @cmdFilt varchar(8000)
SET @cmdfilt = ' WHERE ' 
IF @pCfm <> 1
BEGIN
	IF @An <> 0 
		SET @cmdfilt  = @cmdfilt +  ' (EXISTS (SELECT ContDebit, ContCredit FROM Rulaje'+@strAn+' rj JOIN  RulajeDoc'+@strAn+' rjd ON rj.IDDocument=rjd.IDDocument  WHERE ((ContDebit LIKE Cont + ''%'') OR (ContCredit LIKE Cont + ''%'')) AND rj.[CodUnitate]='+@strCodUnitate+' AND ('+cast(@pJurnal as varchar(10))+'=-1 OR rjd.IDJurnal = '+cast(@pJurnal as varchar(10))+')) OR ((DebInit<>0) OR (CreInit<>0))) '
	ELSE
		SET @cmdfilt  = @cmdfilt +  ' (EXISTS (SELECT ContDebit, ContCredit FROM Rulaje rj  JOIN  RulajeDoc rjd ON rj.IDDocument=rjd.IDDocument WHERE ((ContDebit LIKE Cont + ''%'') OR (ContCredit LIKE Cont + ''%'')) AND rj.[CodUnitate]='+@strCodUnitate+' AND ('+cast(@pJurnal as varchar(10))+'=-1 OR rjd.IDJurnal = '+cast(@pJurnal as varchar(10))+')) OR ((DebInit<>0) OR (CreInit<>0))) '
END

IF @pAnalitica <> 1
BEGIN
	IF @pCfm <> 1
		SET @cmdfilt  = @cmdfilt +  ' AND '
	IF @Tgc=0
		SET @cmdfilt  = @cmdfilt +  ' (([EsteAnalitic]=0)  OR (dbo.IsContIn('',''+ Cont+'','','''+@ConturiSS+''')<>0)) '
	ELSE
		SET @cmdfilt  = @cmdfilt +  ' (([EsteAnalitic]=0) OR (dbo.IsContIn('',''+ Cont+'','','''+@ConturiTGC+''')<>0)) '

END
IF @pCfmRulaje <> 1
BEGIN
	IF (@pCfm <> 1) OR (@pAnalitica <> 1)
		SET @cmdfilt  = @cmdfilt +  ' AND '
	SET @cmdfilt  = @cmdfilt +  ' (DebCurent<>0 OR CreCurent<>0) '
END

IF @pTerminal <> 0
BEGIN
	IF (@pCfm <> 1) OR (@pAnalitica <> 1) OR (@pCfmRulaje <> 1)
		SET @cmdfilt  = @cmdfilt +  ' AND '
	SET @cmdfilt  = @cmdfilt +  '([Terminal]=1)'
END
IF @cmdfilt <> ' WHERE '
	SET @cmd  = @cmd +  @cmdFilt
SET @cmd  = @cmd +  ' ORDER BY Cont '
PRINT(@cmdFilt)
PRINT(@cmd)
EXEC(@cmd) 
IF @@ERROR != 0 GOTO EROARE  GOTO Gata
EROARE:
	ROLLBACK
	RAISERROR ('Eroare balanta!',16,-1)  GOTO Gata
EROARE1:
	RAISERROR ('!!',16,-1)	GOTO Gata
Gata:

END


GO




IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'FaresSetup' AND COLUMN_NAME = 'DataReceptieEgalaDataFactura')
BEGIN
	ALTER TABLE dbo.FaresSetup ADD DataReceptieEgalaDataFactura bit NOT NULL DEFAULT 0
END
GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_GenereazaD394Articole]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_GenereazaD394Articole]
GO


CREATE PROCEDURE [dbo].[fares_GenereazaD394Articole]
	@CUI decimal(13,0),
	@DataStart datetime,
	@DataEnd datetime,
	@cumparari bit,
	@total decimal(20,0) OUT,	
	@totaltva decimal(20,0) OUT	
AS
BEGIN

	SET NOCOUNT ON;
	SELECT @total = sum(TotalValoare),@totaltva=SUM(TotalValoareTVA) FROM 
	(SELECT ROUND(Sum(c.ValoareTotala),0) as TotalValoare, ROUND(sum(c.ValoareTVA),0)  as TotalValoareTVA FROM 
	[Documente] a JOIN Parteneri b ON a.IDPartener = b.IDPartener JOIN
	[DocumenteDetaliu] c ON a.[IDDocument]=c.IDDocument
	JOIN [RegimFiscal] r ON c.IDRegimFiscal = r.IDRegimFiscal
	JOIN [Articole] ar ON c.IDArticol = ar.IDArticol
	WHERE b.CUI = @CUI AND
	DataDoc>= @DataStart AND DataDoc<=@DataEnd  AND RTRIM(LTRIM(b.[AtributFiscal]))='RO'
	AND ((@cumparari=1 AND a.IDTipDocument=0) OR (@cumparari=0 AND a.IDTipDocument=1))
	AND r.IntraIn394=1
	AND c.IDRegimFiscal=6 -- numai cele cu taxare inversa
	AND ar.CodArticol IN ('10011000', '10019010','10019091','10019099','10020000','100300','1005','120100','1205','120600','121291')
	GROUP BY ar.CodArticol) a


	SELECT MAX(ar.CodArticol) as CodPR,
	ROUND(Sum(c.ValoareTotala),0) as BazaPR, ROUND(sum(c.ValoareTotala*c.CotaTVA/100),0)  as TVAPR
	FROM 
	[Documente] a JOIN Parteneri b ON a.IDPartener = b.IDPartener JOIN
	[DocumenteDetaliu] c ON a.[IDDocument]=c.IDDocument
	JOIN [RegimFiscal] r ON c.IDRegimFiscal = r.IDRegimFiscal
	JOIN [Articole] ar ON c.IDArticol = ar.IDArticol
	WHERE b.CUI = @CUI AND
	DataDoc>= @DataStart AND DataDoc<=@DataEnd  AND RTRIM(LTRIM(b.[AtributFiscal]))='RO'
	AND ((@cumparari=1 AND a.IDTipDocument=0) OR (@cumparari=0 AND a.IDTipDocument=1))
	AND r.IntraIn394=1
	AND c.IDRegimFiscal=6 -- numai cele cu taxare inversa
	AND ar.CodArticol IN ('10011000', '10019010','10019091','10019099','10020000','100300','1005','120100','1205','120600','121291')
	GROUP BY ar.CodArticol
END

GO

IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RulajeDocSablon]') AND type in (N'U'))
	BEGIN
	CREATE TABLE [dbo].[RulajeDocSablon](
		[IDSablon] [int] IDENTITY(1,1) NOT NULL,
		[IDTipDocument] [smallint] NULL,
		[IDTipPlata] [smallint] NULL,
		[Descriere] [varchar](250) NOT NULL,
		[OptiuneNumar] [smallint] NULL DEFAULT ((0)),
		[OptiuneData] [smallint] NULL DEFAULT ((0)),
		[TipFormula] [smallint] NOT NULL DEFAULT ((0)),
		[ApplicationName] [nvarchar](256) NOT NULL DEFAULT (''),
		[Tabela] [varchar](100) NULL,
	 CONSTRAINT [PK_RulajeDocSablon] PRIMARY KEY CLUSTERED ([IDSablon] ASC ),
	 CONSTRAINT [FK_RulajeDocSablon_TipDocument] FOREIGN KEY([IDTipDocument]) REFERENCES [dbo].[TipDocument] ([IDTipDocument]),
	 CONSTRAINT [FK_RulajeDocSablon_TipDocumentPlata] FOREIGN KEY([IDTipPlata])REFERENCES [dbo].[TipDocumentPlata] ([IDTipPlata]),
	 CONSTRAINT [FK_RulajeDocSablon_aspnet_Applications] FOREIGN KEY([ApplicationName]) REFERENCES [dbo].[aspnet_Applications] ([ApplicationName])
	) ON [PRIMARY]
	END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[RulajeSablon]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[RulajeSablon](
	[IDSablonRulaj] [int] IDENTITY(1,1) NOT NULL,
	[IDSablon] [int] NOT NULL,
	[OptiuneContDebit] [smallint] NOT NULL DEFAULT ((0)),
	[OptiuneContCredit] [smallint] NOT NULL DEFAULT ((0)),
	[OptiuneValoareLei] [smallint] NOT NULL DEFAULT ((0)),
	[DataDocJust] [datetime] NULL,
	[TipDocJust] [varchar](10) NULL,
	[NumarDocJust] [decimal](18, 0) NULL,
	[ExplicatiiDocJust] [varchar](200) NULL,
 CONSTRAINT [PK_RulajeSablon] PRIMARY KEY CLUSTERED ([IDSablonRulaj] ASC ),
 CONSTRAINT [FK_RulajeSablon_RulajeDocSablon] FOREIGN KEY([IDSablon]) REFERENCES [dbo].[RulajeDocSablon] ([IDSablon]),
) ON [PRIMARY]
END
GO


DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='98A8F7C6-2EFC-402A-9BA3-7A62CD2D0959' AND [HandlerName]='Sabloane_Note_Contabile'
IF @Cate= 0 
BEGIN
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(9011,'98A8F7C6-2EFC-402A-9BA3-7A62CD2D0959','Sabloane Note Contabile',NULL,10,'Sabloane_Note_Contabile',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[balcon_GenExtrasCont]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[balcon_GenExtrasCont]
GO



CREATE PROCEDURE [dbo].[balcon_GenExtrasCont]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint, 
	@DeLaData datetime,
	@PanaLaData datetime,
	@Cod varchar(50),
	@DeLaCont dbo.TipCont,
	@PanaLaCont dbo.TipCont,
	@filtruNrNota varchar(8000)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	IF LEN(@Cod)=0
		SELECT ct.Cont,ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc, 
		ct.DebitInitial - ct.CreditInitial + 
		(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContDebit = ct.Cont) AND rjd.DataDoc<rd.DataDoc )
		-(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContCredit = ct.Cont) AND rjd.DataDoc<rd.DataDoc ) 
		 sodlzi,
		SUM(CASE WHEN ruld.ContDebit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajDebit,
		SUM(CASE WHEN ruld.ContCredit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajCredit
		FROM [Conturi] ct 
		JOIN [Rulaje] ruld ON ct.CodUnitate=ruld.CodUnitate AND (ruld.ContDebit = ct.Cont OR ruld.ContCredit=ct.Cont)
		JOIN [RulajeDoc] rd ON ruld.IDDocument = rd.IDDocument
		WHERE ct.CodUnitate = @CodUnitate AND rd.DataDoc<=@PanaLaData AND 
		rd.DataDoc>=@DeLaData AND 
		(LEN(@DeLaCont)=0 OR ct.Cont >= @DeLaCont) AND (LEN(@PanaLaCont) = 0 OR ct.Cont<=@PanaLaCont) AND
		(LEN(LTRIM(RTRIM(@filtruNrNota)))=0 OR (rd.NumarNota NOT IN (SELECT fart.value FROM dbo.SplitParameters(@filtruNrNota,',') fart)))
		GROUP BY ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc,ct.Cont
		ORDER BY ct.Cont,rd.DataDoc
	ELSE
		SELECT ct.Cont,ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc, 
		ct.DebitInitial - ct.CreditInitial + 
		(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContDebit = ct.Cont) AND rjd.DataDoc<rd.DataDoc )
		-(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje rlj JOIN RulajeDoc rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContCredit = ct.Cont) AND rjd.DataDoc<rd.DataDoc ) 
		 sodlzi,
		SUM(CASE WHEN ruld.ContDebit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajDebit,
		SUM(CASE WHEN ruld.ContCredit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajCredit
		FROM [Conturi] ct 
		JOIN [ConturiSpeciale] cs ON ct.Cont = cs.Cont AND ct.CodUnitate = cs.CodUnitate AND cs.Tipuri LIKE @Cod
		JOIN [Rulaje] ruld ON ct.CodUnitate=ruld.CodUnitate AND (ruld.ContDebit = ct.Cont OR ruld.ContCredit=ct.Cont)
		JOIN [RulajeDoc] rd ON ruld.IDDocument = rd.IDDocument
		WHERE ct.CodUnitate = @CodUnitate AND rd.DataDoc<=@PanaLaData AND rd.DataDoc>=@DeLaData
		AND
		(LEN(LTRIM(RTRIM(@filtruNrNota)))=0 OR (rd.NumarNota NOT IN (SELECT fart.value FROM dbo.SplitParameters(@filtruNrNota,',') fart)))
		GROUP BY ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,rd.DataDoc,ct.Cont
		ORDER BY ct.Cont,rd.DataDoc
END

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GenNotaContabilaUnion]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GenNotaContabilaUnion]
GO


CREATE PROCEDURE [dbo].[GenNotaContabilaUnion]
	-- Add the parameters for the stored procedure here
	@cont TipCont,
	@CodUnitate smallint,
	@DeLaData datetime,
	@PanaLaData datetime,
	@An smallint,
	@strFilter varchar(2000),
	@strFilter2 varchar(2000),
	@strOrder varchar(1000),
	@strFiltruNrNota varchar(2000)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @cmd varchar(5000)
	DECLARE @strCodUnitate varchar(20)
	SET @strCodUnitate = cast(@codUnitate as varchar(20))
	DECLARE @DtDataStartUI varchar(40)
	DECLARE @DtDataEndUI varchar(40)

	SET @DtDataStartUI = cast(YEAR(@DeLaData) as varchar(4)) + '-' +cast(MONTH(@DeLaData) as varchar(2)) + '-' + cast(DAY(@DeLaData) as varchar(2))
	SET @DtDataEndUI = cast(YEAR(@PanaLaData) as varchar(4)) + '-' +cast(MONTH(@PanaLaData) as varchar(2)) + '-' + cast(DAY(@PanaLaData) as varchar(2))

    -- Insert statements for procedure here
	SET @cmd = 'SELECT b.NumarDoc, b.DataDoc, b.NumarNota, a.ContDebit, a.ContCredit, 
                      b.IDJurnal, a.ValoareLei, a.DataDocJust, a.TipDocJust, a.NumarDocJust, a.ExplicatiiDocJust, 
                      b.TipFormula, c.Categorie, ''D'' AS Tip, a.CodUnitate
				FROM  [Rulaje' 
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))
				SET @cmd = @cmd + '] a INNER JOIN  [RulajeDoc'
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))                      
				SET @cmd = @cmd + '] b ON a.IDDocument = b.IDDocument INNER JOIN  [Conturi'
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))                      
				SET @cmd = @cmd + '] c ON a.ContDebit = c.Cont AND c.CodUnitate = a.CodUnitate
				WHERE [ContDebit]<>''N/A'' AND (a.CodUnitate = ' + @strCodUnitate + ') ' 
				IF @cont<> ''
					SET @cmd = @cmd + ' AND (a.ContDebit like ''' + @cont + '%'' OR a.ContCredit like ''' + @cont + '%'')'

				SET @cmd = @cmd + ' AND (b.DataDoc >=''' +	@DtDataStartUI + ''' AND b.DataDoc<='''	 +  @DtDataEndUI + ''')'

				IF @strFilter <> ''
					SET @cmd = @cmd + @strFilter

				IF @strFiltruNrNota	<> ''
					SET @cmd = @cmd + ' AND b.NumarNota not in (' + @strFiltruNrNota + ') '

--				IF @strOrder = ''
--					SET @cmd = @cmd + 'ORDER BY b.DataDoc'
--				ELSE
--					SET @cmd = @cmd + @strOrder
		SET @cmd = @cmd + '  UNION SELECT b.NumarDoc, b.DataDoc, b.NumarNota, a.[ContCredit] AS [ContDebit], a.[ContDebit] AS ContCredit, 
                      b.IDJurnal, a.ValoareLei, a.DataDocJust, a.TipDocJust, a.NumarDocJust, a.ExplicatiiDocJust, 
                      b.TipFormula, c.Categorie, ''C'' AS Tip, a.CodUnitate
				FROM  [Rulaje' 
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))
				SET @cmd = @cmd + '] a INNER JOIN  [RulajeDoc'
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))                      
				SET @cmd = @cmd + '] b ON a.IDDocument = b.IDDocument INNER JOIN  [Conturi'
				IF @An <> 0 
					  SET @cmd = @cmd + cast(@an as varchar(4))                      
				SET @cmd = @cmd + '] c ON a.ContDebit = c.Cont AND c.CodUnitate = a.CodUnitate
				WHERE [ContCredit]<>''N/A'' AND (a.CodUnitate = ' + @strCodUnitate + ') ' 
				IF @cont<> ''
					SET @cmd = @cmd + ' AND (a.ContDebit like ''' + @cont + '%'' OR a.ContCredit like ''' + @cont + '%'')'

				SET @cmd = @cmd + ' AND (b.DataDoc >=''' +	@DtDataStartUI + ''' AND b.DataDoc<='''	 +  @DtDataEndUI + ''')'

				IF @strFilter2 <> ''
					SET @cmd = @cmd + @strFilter2
					
				IF @strFiltruNrNota	<> ''
					SET @cmd = @cmd + ' AND b.NumarNota NOT in (' + @strFiltruNrNota + ') '
					
				IF @strOrder = ''
					SET @cmd = @cmd + 'ORDER BY b.DataDoc'
				ELSE
					SET @cmd = @cmd + @strOrder
    PRINT(@cmd)		
	EXEC(@Cmd) 
	IF @@ERROR != 0 GOTO EROARE	





	GOTO Gata
	EROARE:
		RAISERROR ('Eroare la generarea datelor pentru [NotaContabilaView]!',16,-1)
		GOTO Gata
	Gata:

END

GO


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_viewSumeCategorii]'))
DROP VIEW [dbo].[fares_viewSumeCategorii]
GO


CREATE VIEW [dbo].[fares_viewSumeCategorii]
AS
SELECT     dbo.TipCategoriiArticole.Denumire, dbo.Documente.DataDoc, SUM(dbo.DocumenteDetaliu.ValoareTotala) AS ValoareTotala, dbo.DocumenteDetaliu.CodUnitate, 
                      dbo.Articole.Denumire AS DenumireArticol, dbo.Departamente.Nume AS DenDepartament, dbo.Jurnale.Denumire AS DenumireJurnal, dbo.Documente.IDPartener, 
                      dbo.Articole.IDArticol, dbo.Documente.IDTipDocument, dbo.DocumenteDetaliu.ValoareUnitara, dbo.DocumenteDetaliu.Cantitate
FROM         dbo.Articole INNER JOIN
                      dbo.DocumenteDetaliu ON dbo.Articole.IDArticol = dbo.DocumenteDetaliu.IDArticol INNER JOIN
                      dbo.TipCategoriiArticole ON dbo.Articole.IDCategorie = dbo.TipCategoriiArticole.IDCategorie INNER JOIN
                      dbo.Documente ON dbo.DocumenteDetaliu.IDDocument = dbo.Documente.IDDocument LEFT OUTER JOIN
                      dbo.Departamente ON dbo.Documente.IDDepartament = dbo.Departamente.IDDepartament LEFT OUTER JOIN
                      dbo.Jurnale ON dbo.Departamente.IDJurnal = dbo.Jurnale.IDJurnal
WHERE     (dbo.Documente.IDTipDocument = 9)
GROUP BY dbo.TipCategoriiArticole.Denumire, dbo.Documente.DataDoc, dbo.DocumenteDetaliu.CodUnitate, dbo.Articole.Denumire, dbo.Departamente.Nume, 
                      dbo.Jurnale.Denumire, dbo.Documente.IDPartener, dbo.Documente.CodUnitate, dbo.Articole.IDArticol, dbo.Documente.IDTipDocument, 
                      dbo.DocumenteDetaliu.ValoareUnitara, dbo.DocumenteDetaliu.Cantitate

GO



UPDATE [Ordonantari]
SET DataDoc = cast(cast(YEAR(DataDoc) as varchar(4)) + '-' +cast(MONTH(DataDoc) as varchar(2)) + '-' + cast(DAY(DataDoc) as varchar(2)) as datetime)
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[balcon_GenRegistruCasaArhiva]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[balcon_GenRegistruCasaArhiva]
GO


CREATE PROCEDURE [dbo].[balcon_GenRegistruCasaArhiva]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint, 
	@DeLaData datetime,
	@PanaLaData datetime,
	@Cod varchar(50),
	@DataDocJust bit,
	@an varchar(4)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	DECLARE @DtDataStartUI varchar(20)
	DECLARE @DtDataEndUI varchar(20)
	DECLARE @strCodUnitate varchar(20)
	
	SET @DtDataStartUI = cast(YEAR(@DeLaData) as varchar(4)) + '-' +cast(MONTH(@DeLaData) as varchar(2)) + '-' + cast(DAY(@DeLaData) as varchar(2))
	SET @DtDataEndUI = cast(YEAR(@PanaLaData) as varchar(4)) + '-' +cast(MONTH(@PanaLaData) as varchar(2)) + '-' + cast(DAY(@PanaLaData) as varchar(2))

	SET @strCodUnitate = cast(@CodUnitate AS varchar(20))
	SET NOCOUNT ON;
	
	DECLARE @cmd varchar(5000)
	SET @cmd = 'SELECT ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,'
	IF @DataDocJust=1
		SET @cmd = @cmd +'ruld.DataDocJust As DataDoc,'
	ELSE
		SET @cmd = @cmd +' rd.DataDoc,'
	SET @cmd =@cmd + 'ct.DebitInitial - ct.CreditInitial + 
		(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje'+@an+' rlj JOIN RulajeDoc'+@an+' rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContDebit = ct.Cont) AND rjd.DataDoc<rd.DataDoc )
		-(SELECT COALESCE(SUM(rlj.ValoareLei),0) FROM Rulaje'+@an+' rlj JOIN RulajeDoc'+@an+' rjd ON rlj.IDDocument = rjd.IDDocument
		WHERE rlj.CodUnitate = ct.CodUnitate AND (rlj.ContCredit = ct.Cont) AND rjd.DataDoc<rd.DataDoc ) 
			sodlzi,
		SUM(CASE WHEN ruld.ContDebit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajDebit,
		SUM(CASE WHEN ruld.ContCredit=ct.Cont THEN ruld.ValoareLei ELSE 0 END) rulajCredit
		FROM [Conturi'+@an+'] ct 
		LEFT OUTER JOIN [ConturiSpeciale] cs ON ct.Cont = cs.Cont AND ct.CodUnitate = cs.CodUnitate 
		JOIN [Rulaje'+@an+'] ruld ON ct.CodUnitate=ruld.CodUnitate AND (ruld.ContDebit = ct.Cont OR ruld.ContCredit=ct.Cont)
		JOIN [RulajeDoc'+@an+'] rd ON ruld.IDDocument = rd.IDDocument
		WHERE ct.CodUnitate = '+@strCodUnitate+' AND rd.DataDoc>='''+@DtDataStartUI+''' AND rd.DataDoc<='''+@DtDataEndUI+'''
		AND (LEN('''+@Cod+''')=0 OR cs.Tipuri LIKE '''+@Cod+''')
		GROUP BY ct.CodUnitate,ct.DebitInitial,ct.CreditInitial,'
	IF @DataDocJust=1
		SET @cmd = @cmd +'ruld.DataDocJust,ct.Cont'
	ELSE
		SET @cmd = @cmd +'rd.DataDoc,ct.Cont'
	PRINT @Cmd	
	EXEC(@cmd) 
	IF @@ERROR != 0 GOTO EROARE  GOTO Gata
	EROARE:
		ROLLBACK
		RAISERROR ('Eroare registru casa!',16,-1)  GOTO Gata
	EROARE1:
		RAISERROR ('!!',16,-1)	GOTO Gata
	Gata:	
		
	
		
END
GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[AmixViewIesite]'))
DROP VIEW [dbo].[AmixViewIesite]
GO


CREATE VIEW [dbo].[AmixViewIesite]
AS
SELECT     dbo.AmixRegistru.NrInventar, dbo.AmixRegistru.Denumire, dbo.AmixRegistru.ContAmortizare, dbo.AmixCatalog.Cod, dbo.AmixRegistru.DataIntrare, 
                      dbo.AmixRegistru.DataIesire, dbo.AmixRegistru.CodUnitate, dbo.Departamente.Nume, dbo.AmixRegistru.ContImobilizare, dbo.AmixRegistru.ContCheltuiala, 
                      dbo.AmixRegistru.DurataAmortizare, dbo.AmixRegistru.RegimAmortizare, dbo.AmixRegistru.ValoareInventar, dbo.AmixRegistru.ValoareAmortizata, 
                      0 AS ValoareRamasa, 0 AS AmortizareLuna, dbo.AmixRegistru.DurataAmortizare AS DurataNormata, dbo.AmixRegistru.LuniAmortizate, 
                      dbo.AmixTipStare.Denumire AS Stare, 0 AS Luna, 0 AS An, dbo.AmixRegistru.Blocat, dbo.AmixRegistru.Compus, 0 AS AmortizareBlocata, 
                      dbo.AmixRegistru.IDMijlocFix, dbo.AmixGestionari.Nume AS Gestionar, dbo.AmixRegistru.IDStare, dbo.AmixRegistru.StocFaptic, dbo.AmixRegistru.Categorie, 
                      dbo.AmixCatalog.Grupa, dbo.Departamente.IDDepartament, dbo.AmixRegistru.ContTransferForSuperior, dbo.AmixRegistru.ValoareIntrataTransfer, 
                      dbo.Jurnale.Codificare
FROM         dbo.AmixRegistru LEFT OUTER JOIN
                      dbo.Jurnale ON dbo.AmixRegistru.IDJurnal = dbo.Jurnale.IDJurnal LEFT OUTER JOIN
                      dbo.Departamente ON dbo.AmixRegistru.IDDepartament = dbo.Departamente.IDDepartament LEFT OUTER JOIN
                      dbo.AmixCatalog ON dbo.AmixRegistru.IDClasificare = dbo.AmixCatalog.IDClasificare LEFT OUTER JOIN
                      dbo.AmixTipStare ON dbo.AmixRegistru.IDStare = dbo.AmixTipStare.IDStare LEFT OUTER JOIN
                      dbo.AmixGestionari ON dbo.AmixRegistru.IDGestionar = dbo.AmixGestionari.IDGestionar
WHERE     (dbo.AmixRegistru.IDStare <> 5)

GO




IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[AmixViewRegistru]'))
DROP VIEW [dbo].[AmixViewRegistru]
GO



CREATE VIEW [dbo].[AmixViewRegistru]
AS
SELECT     dbo.AmixRegistru.NrInventar, dbo.AmixRegistru.Denumire, dbo.AmixRegistru.ContAmortizare, dbo.AmixCatalog.Cod, dbo.AmixRegistru.DataIntrare, 
                      dbo.AmixRegistru.DataIesire, dbo.AmixRegistru.CodUnitate, dbo.Departamente.Nume, dbo.AmixRegistru.ContImobilizare, dbo.AmixRegistru.ContCheltuiala, 
                      dbo.AmixRegistru.DurataAmortizare, dbo.AmixRegistru.RegimAmortizare, COALESCE (dbo.AmixAmortizare.ValoareInventar, dbo.AmixRegistru.ValoareInventar) 
                      AS ValoareInventar, COALESCE (dbo.AmixAmortizare.ValoareAmortizata, dbo.AmixRegistru.ValoareInventar) AS ValoareAmortizata, 
                      COALESCE (dbo.AmixAmortizare.ValoareRamasa, 0) AS ValoareRamasa, dbo.AmixAmortizare.AmortizareLuna, dbo.AmixAmortizare.DurataNormata, 
                      dbo.AmixAmortizare.LuniAmortizate, dbo.AmixTipStare.Denumire AS Stare, COALESCE (dbo.AmixAmortizare.Luna, 0) AS Luna, COALESCE (dbo.AmixAmortizare.An, 0) 
                      AS An, dbo.AmixRegistru.Blocat, dbo.AmixRegistru.Compus, COALESCE (dbo.AmixAmortizare.Blocat, 0) AS AmortizareBlocata, dbo.AmixRegistru.IDMijlocFix, 
                      dbo.AmixGestionari.Nume AS Gestionar, dbo.AmixRegistru.IDStare, dbo.AmixRegistru.StocFaptic, dbo.AmixRegistru.Categorie, dbo.AmixCatalog.Grupa, 
                      dbo.Departamente.IDDepartament, dbo.AmixRegistru.ContTransferForSuperior, dbo.AmixRegistru.ValoareIntrataTransfer, dbo.Jurnale.Codificare
FROM         dbo.AmixRegistru LEFT OUTER JOIN
					  dbo.Jurnale ON dbo.AmixRegistru.IDJurnal = dbo.Jurnale.IDJurnal LEFT OUTER JOIN
                      dbo.AmixAmortizare ON dbo.AmixAmortizare.IDMijlocFix = dbo.AmixRegistru.IDMijlocFix LEFT OUTER JOIN
                      dbo.AmixCatalog ON dbo.AmixRegistru.IDClasificare = dbo.AmixCatalog.IDClasificare LEFT OUTER JOIN
                      dbo.Departamente ON dbo.AmixRegistru.IDDepartament = dbo.Departamente.IDDepartament LEFT OUTER JOIN
                      dbo.AmixTipStare ON dbo.AmixRegistru.IDStare = dbo.AmixTipStare.IDStare LEFT OUTER JOIN
                      dbo.AmixGestionari ON dbo.AmixRegistru.IDGestionar = dbo.AmixGestionari.IDGestionar

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CalcDisponibilOrdRows]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[CalcDisponibilOrdRows]
GO

CREATE PROCEDURE [dbo].[CalcDisponibilOrdRows]  
	@IDClasificare int, 
	@Analitic TipCont,
	@PanaLa DateTime,
	@CodDoc int,
	@CodUnitate smallint
AS 
begin
	DECLARE @strEroare AS varchar(200)

	DECLARE @cont TipCont
	DECLARE @cont2 TipCont

	SET @cont ='8062.'+@Analitic
	SET @cont2 ='7701.'+@Analitic
	SELECT NumarDoc, DataDoc, coalesce(r.ValoareLei,0) ValoareLeiDebit, 0  ValoareLeiCredit, ContDebit Cont FROM Rulaje r
	JOIN RulajeDoc d ON r.IDDocument = d.IDDocument AND IDJurnal = @IDClasificare AND d.[CodUnitate] = @CodUnitate AND (d.DataDoc<@PanaLa or ( d.DataDoc=@PanaLa AND (d.IDDocument<@CodDoc OR @CodDoc=0) ))  
	WHERE  ContDebit=@cont
    UNION		
	SELECT NumarDoc, DataDoc, 0 ValoareLeiDebit, coalesce(r.ValoareLei,0) ValoareLeiCredit, ContCredit Cont FROM Rulaje r
	JOIN RulajeDoc d ON r.IDDocument = d.IDDocument AND
		IDJurnal = @IDClasificare  AND d.[CodUnitate] = @CodUnitate AND (d.DataDoc<@PanaLa or ( d.DataDoc=@PanaLa AND (d.IDDocument<@CodDoc OR @CodDoc=0) )) 
	WHERE ContCredit=@cont
	--@totDebitPla	
	UNION
	SELECT NumarDoc, DataDoc,coalesce(r.ValoareLei,0) ValoareLeiDebit, 0 ValoareLeiCredit, ContDebit Cont FROM [Rulaje] r 
	JOIN RulajeDoc d ON  r.IDDocument = d.IDDocument AND
		IDJurnal = @IDClasificare AND d.[CodUnitate] = @CodUnitate AND DataDoc<@PanaLa
	WHERE ContDebit= @cont2 AND r.TipDocJust<>'IC'
    --@totCreditPla
    UNION
	SELECT NumarDoc, DataDoc,0 ValoareLeiDebit, coalesce(r.ValoareLei,0) ValoareLeiCredit, ContCredit Cont FROM [Rulaje] r 
	JOIN RulajeDoc d ON r.IDDocument = d.IDDocument AND
		 IDJurnal = @IDClasificare AND d.[CodUnitate] = @CodUnitate AND DataDoc<@PanaLa
    WHERE ContCredit=@cont2 AND r.TipDocJust<>'IC'
    --@totOrdonantat
    UNION
	SELECT NrDoc, DataDoc,0 ValoareLeiDebit, coalesce(ValoareLei,0) ValoareLeiCredit, 'ORDONANTARE' Cont FROM [Ordonantari] WHERE  (DataDoc<@PanaLa 
			OR (DataDoc=@PanaLa  AND IDOrdonantare<@CodDoc)) AND ArtAl Like @Analitic+'%'
			AND IDJurnal=@IDClasificare AND [CodUnitate] = @CodUnitate AND Achitat=0	
	ORDER BY DataDoc
	--SET @s944 = @totDebit + @totDebitPla - @totCredit - @totCreditPla - @totOrdonantat
    --PRINT (@totOrdonantat)


	 GOTO Gata
Eroare:
	 RAISERROR (@strEroare,16,-1)
Gata:
end

GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[AmixViewToate]'))
DROP VIEW [dbo].[AmixViewToate]
GO

CREATE VIEW [dbo].[AmixViewToate]
AS
SELECT     [NrInventar]
      ,[Denumire]
      ,[ContAmortizare]
      ,[Cod]
      ,[DataIntrare]
      ,[DataIesire]
      ,[CodUnitate]
      ,[Nume]
      ,[ContImobilizare]
      ,[ContCheltuiala]
      ,[DurataAmortizare]
      ,[RegimAmortizare]
      ,[ValoareInventar]
      ,[ValoareAmortizata]
      ,[ValoareRamasa]
      ,[AmortizareLuna]
      ,[DurataNormata]
      ,[LuniAmortizate]
      ,[Stare]
      ,[Luna]
      ,[An]
      ,[Blocat]
      ,[Compus]
      ,[AmortizareBlocata]
      ,[IDMijlocFix]
      ,[Gestionar]
      ,[IDStare]
      ,[StocFaptic]
      ,[Categorie]
      ,[Grupa]
      ,[IDDepartament]
      ,[ContTransferForSuperior]
      ,[ValoareIntrataTransfer]
      ,[Codificare]
FROM         dbo.AmixViewRegistru
UNION
SELECT     [NrInventar]
      ,[Denumire]
      ,[ContAmortizare]
      ,[Cod]
      ,[DataIntrare]
      ,[DataIesire]
      ,[CodUnitate]
      ,[Nume]
      ,[ContImobilizare]
      ,[ContCheltuiala]
      ,[DurataAmortizare]
      ,[RegimAmortizare]
      ,[ValoareInventar]
      ,[ValoareAmortizata]
      ,[ValoareRamasa]
      ,[AmortizareLuna]
      ,[DurataNormata]
      ,[LuniAmortizate]
      ,[Stare]
      ,[Luna]
      ,[An]
      ,[Blocat]
      ,[Compus]
      ,[AmortizareBlocata]
      ,[IDMijlocFix]
      ,[Gestionar]
      ,[IDStare]
      ,[StocFaptic]
      ,[Categorie]
      ,[Grupa]
      ,[IDDepartament]
      ,[ContTransferForSuperior]
      ,[ValoareIntrataTransfer]
      ,[Codificare]
FROM         dbo.AmixViewIesite

GO

DECLARE @cate int
SELECT @Cate = COUNT(*) FROM [admin_ApplicationMenu] WHERE [ApplicationId]='98A8F7C6-2EFC-402A-9BA3-7A62CD2D0959' AND [HandlerName]='Semnaturi'
IF @Cate= 0 
BEGIN
	SET IDENTITY_INSERT [admin_ApplicationMenu] ON
	INSERT INTO [admin_ApplicationMenu] ([IDMeniuAplicatie],[ApplicationId],[Name],[IdMeniuParinte],[Ordine],[HandlerName],[Tag],[Vizibil])VALUES(9731,'98A8F7C6-2EFC-402A-9BA3-7A62CD2D0959','Semnaturi',9006,130,'Semnaturi',NULL,NULL)
	SET IDENTITY_INSERT [admin_ApplicationMenu] OFF
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[amix_spViewRegistru]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[amix_spViewRegistru]
GO


CREATE PROCEDURE [dbo].[amix_spViewRegistru]
	-- Add the parameters for the stored procedure here
	@filtru varchar(1000), 
	@an smallint,
	@luna smallint
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    DECLARE @cmd varchar(8000)
    SET @cmd =
	' SELECT  *  FROM (SELECT  ar.NrInventar, ar.Denumire, ar.ContAmortizare, ar.DataIntrare, ar.DataIesire, 
                      ar.CodUnitate,  ar.ContImobilizare, ar.ContCheltuiala, ar.DurataAmortizare, ar.IDMijlocFix,
                      ar.RegimAmortizare, ar.ValoareInventar, 
                      ar.Compus,ar.StocFaptic, ar.Categorie,ar.Blocat,ar.IDStare,
                      dbo.Departamente.Nume,
                      COALESCE (aa.ValoareAmortizata,CASE WHEN YEAR(ar.PunereInFunctiune)*100 + MONTH(ar.PunereInFunctiune) < '+CAST(@An*100+@luna AS varchar(6))+' THEN ar.ValoareInventar ELSE ar.ValoareAmortizata END) AS ValoareAmortizata, 
                      COALESCE (aa.ValoareRamasa, 0) AS ValoareRamasa, COALESCE (aa.AmortizareLuna, 0) AS AmortizareLuna, COALESCE (aa.DurataNormata, 0) 
                      AS DurataNormata, aa.LuniAmortizate, COALESCE (aa.Luna, 0) AS Luna, COALESCE (aa.An, 0) AS An, 
                      COALESCE (aa.Blocat, 0) AS AmortizareBlocata,
                      dbo.AmixTipStare.Denumire AS Stare, 
                      dbo.AmixGestionari.Nume AS Gestionar, 
                      dbo.AmixCatalog.Cod,dbo.AmixCatalog.Grupa,ContTransferForSuperior, ValoareIntrataTransfer,j.Codificare
		FROM  dbo.AmixRegistru ar 
					  LEFT OUTER JOIN 
					  (SELECT * FROM AmixAmortizare aa WHERE aa.Luna='+CAST(@Luna AS varchar(2))+' and aa.An= ' + cast(@An as varchar(4)) + ') aa  ON ar.IDMijlocFix = aa.IDMijlocFix 
                      LEFT OUTER JOIN  dbo.AmixCatalog ON ar.IDClasificare = dbo.AmixCatalog.IDClasificare 
                      LEFT OUTER JOIN dbo.Departamente ON ar.IDDepartament = dbo.Departamente.IDDepartament 
                      LEFT OUTER JOIN dbo.AmixTipStare ON ar.IDStare = dbo.AmixTipStare.IDStare 
					  LEFT OUTER JOIN dbo.Jurnale j ON ar.IDJurnal = j.IDJurnal 
                      LEFT OUTER JOIN dbo.AmixGestionari ON ar.IDGestionar = dbo.AmixGestionari.IDGestionar) fs '
     IF @filtru <> ''
		SET @cmd = @cmd + ' WHERE ' + @filtru
     EXEC(@cmd) 
 
END

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fares_FiltreazaRaportFacturi]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[fares_FiltreazaRaportFacturi]
GO


CREATE PROCEDURE [dbo].[fares_FiltreazaRaportFacturi] 
    @filtruPart varchar(8000),
    @filtruDoc varchar(8000),
	@data1 datetime,
	@data2 datetime,
	@datasold datetime,
	@facturiSold bit,
	@totalNeachitate bit,
	@integralAchitate bit,
	@CodUnitate smallint
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	SELECT * FROM 
	(SELECT     a.IDPartener, a.NrDoc, a.DataDoc, ROUND(a.Total, 2) AS Total, ROUND(a.TotalValoare, 2) AS TotalValoare, ROUND(a.TotalValoareTVA, 2) AS TotalValoareTVA, COALESCE (b.Valoare, 0) AS Valoare, ROUND(a.Total, 2) - COALESCE (b.Valoare, 0) AS RestPlata, 
               a.DataScadenta, dbo.Parteneri.Denumire, a.IDTipDocument, a.CodUnitate, cast(a.IDDocument AS Varchar(50)) AS IDDocument, a.CotaTVA
		FROM         dbo.Documente AS a LEFT OUTER JOIN
                          (SELECT     IDDocument, SUM(Valoare) AS Valoare
                            FROM          dbo.DocumentePlataDetaliu dpd JOIN DocumentePlata dp ON dpd.IDDocumentPlata=dp.IDDocumentPlata WHERE Data<=@datasold
                            GROUP BY IDDocument ) AS b ON a.IDDocument = b.IDDocument INNER JOIN
                      dbo.Parteneri ON a.IDPartener = dbo.Parteneri.IDPartener) a WHERE 
     (LEN(LTRIM(RTRIM(@filtruPart)))=0 OR (IDPartener IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruPart,',') fart))) AND           
     (LEN(LTRIM(RTRIM(@filtruDoc)))=0 OR (IDTipDocument IN (SELECT fart.value FROM dbo.SplitBigIntParameters(@filtruDoc,',') fart))) AND
	 CodUnitate = @CodUnitate AND [DataDoc]>=@data1 AND [DataDoc]<=@data2 AND
	 (@facturiSold=0 OR (@facturiSold=1 AND [RestPlata] <> 0)) AND
	 (@totalNeachitate=0 OR (@totalNeachitate=1 AND [RestPlata] = [Total])) AND 
	 (@integralAchitate=0 OR (@integralAchitate=1 AND  [RestPlata] = [Valoare]))
	 
	 ORDER BY [DataDoc]

END

GO

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[fares_Facturi]'))
DROP VIEW [dbo].[fares_Facturi]
GO


CREATE VIEW [dbo].[fares_Facturi]
AS
SELECT     a.IDPartener, a.NrDoc, a.DataDoc, ROUND(a.TotalValoare, 2) AS TotalValoare, ROUND(a.TotalValoareTVA, 2) AS TotalValoareTVA, ROUND(a.Total, 2) AS Total, 
                      COALESCE (b.Valoare, 0) AS Valoare, ROUND(a.Total, 2) - COALESCE (b.Valoare, 0) AS RestPlata, a.DataScadenta, dbo.Parteneri.Denumire, a.IDTipDocument, 
                      a.CodUnitate, CAST(a.IDDocument AS varchar(50)) AS IDDocument, a.CotaTVA
FROM         dbo.Documente AS a LEFT OUTER JOIN
                          (SELECT     IDDocument, SUM(Valoare) AS Valoare
                            FROM          dbo.DocumentePlataDetaliu
                            GROUP BY IDDocument) AS b ON a.IDDocument = b.IDDocument INNER JOIN
                      dbo.Parteneri ON a.IDPartener = dbo.Parteneri.IDPartener

GO



IF NOT  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ExecutieCheltuieli]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[ExecutieCheltuieli](
	[IDExecutieCheltuieli] [int] IDENTITY(1,1) NOT NULL,
	[ArtAl] [varchar](40) NOT NULL,
	[Data] [datetime] NOT NULL,
	[Valoare] [decimal](28, 5) NOT NULL,
	[CodUnitate] [smallint] NOT NULL,
	[IDJurnal] [int] NULL,
	[IDDepartament] [int] NOT NULL,
 CONSTRAINT [PK_ExecutieCheltuieli] PRIMARY KEY CLUSTERED ([IDExecutieCheltuieli] ASC),
 CONSTRAINT [FK_ExecutieCheltuieli_ArticoleAliniate] FOREIGN KEY([ArtAl], [CodUnitate]) REFERENCES [dbo].[ArticoleAliniate] ([ArtAl], [CodUnitate]),
 CONSTRAINT [FK_ExecutieCheltuieli_Departamente] FOREIGN KEY([IDDepartament]) REFERENCES [dbo].[Departamente] ([IDDepartament]),
 CONSTRAINT [FK_ExecutieCheltuieli_Jurnale] FOREIGN KEY([IDJurnal]) REFERENCES [dbo].[Jurnale] ([IDJurnal])
) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'ArticoleAliniate' AND COLUMN_NAME = 'ExecutieCheltuieli')
BEGIN
	ALTER TABLE dbo.ArticoleAliniate ADD ExecutieCheltuieli bit NOT NULL DEFAULT 0
END
GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AmixDocumente' AND COLUMN_NAME = 'IDUnitateMasura')
BEGIN
	ALTER TABLE dbo.AmixDocumente ADD IDUnitateMasura smallint NULL
END
GO

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'AmixDocumente' AND COLUMN_NAME = 'ContTransferForSuperior')
BEGIN
	ALTER TABLE dbo.AmixDocumente ADD ContTransferForSuperior varchar(50) NULL
END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[amix_InchideLuna2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[amix_InchideLuna2]
GO

CREATE PROCEDURE [dbo].[amix_InchideLuna2] 
	-- Add the parameters for the stored procedure here
	@Luna smallint, 
	@An smallint,
	@CodUnitate smallint,
	@IDDocument int, --daca document e zero pe toate
	@InchideLuna bit --daca se inchide luna sau nu
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	--SET NOCOUNT ON;
	-- numarul mijloacelor fixe cu acelasi numar de inventar
	DECLARE @MaxDurata int
	DECLARE @Index int
	DECLARE @Compus int
	DECLARE @UltimaZiLuna datetime
	DECLARE @LunaCurenta smallint 
	DECLARE @AnCurent smallint

	SELECT @LunaCurenta =LunaCurenta, @AnCurent=AnulCurent  FROM AmixSetup WHERE CodUnitate=@CodUnitate

	SET @UltimaZiLuna = DATEADD(day,-1,DATEADD(month,1,CAST(CAST(@An AS varchar(4)) + '-' + CAST(@Luna AS varchar(2)) + '-01' AS datetime)))
 
 
	IF @IDDocument=0
		SET @Compus = 1
	ELSE
		--daca documentul a fost sters le actualizeaza pe toate!
		SELECT @Compus = ISNULL([Compus],1) FROM [AmixDocumente] WHERE  [IDDocument]=@IDDocument	
	PRINT('Compus=' + cast(@Compus as varchar(2)))
	--sterge mijloacele fixe introduse in luna curenta
	BEGIN TRAN
	
	---sterge din tabela de amortizari inregistrarile generate
	-- daca suntem dupa luna curenta
	IF @AnCurent*12 + @LunaCurenta <= @An*12+@Luna
	BEGIN
		DELETE FROM [AmixAmortizare] WHERE [IDMijlocFix] IN (SELECT [IDMijlocFix] FROM [AmixRegistru]
			WHERE [CodUnitate]=@CodUnitate) AND [An] = @An AND [Luna]=@Luna
		IF @@ERROR <>0 GOTO Eroare  
	
		DELETE FROM [AmixRegistruBK] WHERE  [CodUnitate]=@CodUnitate AND [An] = @An AND [Luna]=@Luna
		IF @@ERROR <>0 GOTO Eroare  	

		---------------------------------------------------------------------------------------------------
		----------------------------------------Backup-----------------------------------------------------
		--- se salveaza toate mijloacele fixe
		INSERT INTO [AmixRegistruBK]
			   ([IDMijlocFix],[NrInventar],[Denumire],[ContAmortizare],[StocFaptic],[IDClasificare],[DataIntrare],[DataIesire],[CodUnitate],[IDDepartament],[IDStare]
				,[ContImobilizare],[ContCheltuiala],[DurataAmortizare],[RegimAmortizare],[ValoareInventar],[PunereInFunctiune],[Compus] ,[Blocat]
				,[IDGestionar],[ContTransfer],[ValoareAmortizata],[LuniAmortizate],[AmortizareLuna],[AmortizareAn],[InFolosinta],[CantitateOI]
				,[Categorie],[IDUnitateMasura],Luna,An,[ContTransferForSuperior],[IDJurnal],[ValoareIntrataTransfer])
				SELECT [IDMijlocFix],[NrInventar],[Denumire],[ContAmortizare],[StocFaptic],[IDClasificare],[DataIntrare],[DataIesire],[CodUnitate],[IDDepartament],[IDStare]
				,[ContImobilizare],[ContCheltuiala],[DurataAmortizare],[RegimAmortizare],[ValoareInventar],[PunereInFunctiune],[Compus] ,[Blocat]
				,[IDGestionar],[ContTransfer],[ValoareAmortizata],[LuniAmortizate],[AmortizareLuna],[AmortizareAn],[InFolosinta],[CantitateOI]
				,[Categorie],[IDUnitateMasura],@LunaCurenta,@AnCurent,[ContTransferForSuperior],[IDJurnal],[ValoareIntrataTransfer]
			   FROM [AmixRegistru] a 
			WHERE  [CodUnitate]=@CodUnitate 
		IF @@ERROR <>0 GOTO Eroare  	

		UPDATE [AmixDocumente] SET [IDBK] = b.[IDBK] FROM [AmixRegistruBK] b 
		WHERE [AmixDocumente].[NrInventar] = b.[NrInventar] AND [AmixDocumente].[CodUnitate] = b.[CodUnitate]
		IF @@ERROR <>0 GOTO Eroare  	

		----------------------------------------Backup-----------------------------------------------------
	
	END
	
	---------------------------------------------------------------------------------------------------

	--nu se pot sterge inregistrarile din registru pentru ca sunt legate de amortizare
	-- ele se updateaza mijloacele fixe existente
	-------------------------------------------------------------------------------
	UPDATE [AmixRegistru] 
			SET [NrInventar] = d.[NrInventar],
			[Denumire]=d.[Denumire],
			[ContAmortizare]=d.[ContAmortizare],
			[StocFaptic]=1,
			[IDClasificare]=d.[IDClasificare],
            [DataIntrare]=CASE WHEN d.Compus<3 THEN DATEADD(month,1,d.[PunereInFunctiune]) ELSE d.[DataDoc] END,
            [DataIesire]=DATEADD(month,d.[DurataAmortizare]-d.[LuniAmortizate],d.[PunereInFunctiune]),
			[CodUnitate]=@CodUnitate,
			[IDDepartament]=d.[IDDepartament],
			[IDStare]=5,
			[ContImobilizare]=d.[ContImobilizare],
			[ContCheltuiala]=d.[ContCheltuiala],
			[DurataAmortizare]=d.[DurataAmortizare],
			[RegimAmortizare]=d.[RegimAmortizare],
			[ValoareInventar]=d.[ValoareInventar],
			[PunereInFunctiune]=d.[PunereInFunctiune],[Compus]=d.[Compus],
			[IDGestionar]=d.[IDGestionar],
			[AmortizareLuna] = d.[AmortizareLuna],
			[AmortizareAn] = d.[AmortizareAn], -- de fapt este vorba de amortizarea in primul an
			[ValoareAmortizata] = d.ValoareAmortizata,
			[IDUnitateMasura] = d.[IDUnitateMasura],
			[CantitateOI] = d.CantitateOI,
			[InFolosinta] = d.[InFolosinta],
			[ContTransferForSuperior] = d.[ContTransferForSuperior]
			FROM [AmixDocumente] d
	WHERE  
		d.[Anul] = @An AND d.[Luna]=@Luna AND d.[CodUnitate]=@CodUnitate AND d.[IDTipDocument]=2 AND d.[IDMijlocFix] = [AmixRegistru].[IDMijlocFix] AND d.[IDMijlocFix] IS NOT NULL
		AND (@IDDocument=0 OR [IDDocument]=@IDDocument)
	IF @@ERROR <>0 GOTO Eroare  	
	--pentru modernizare
	PRINT('actualizarile pentru modernizare in registru')
    --atentie se modifica si mortizarea lunara si Amorizarea anuala
	UPDATE [AmixRegistru] 
			SET [DurataAmortizare]=d.[DurataAmortizare]+ d.[DurExtindere],[ValoareInventar]=d.[ValoareInventar] + d.[ValoareSuplimentara],
            [AmortizareLuna] = CASE WHEN [AmixRegistru].[RegimAmortizare]= 1 THEN d.[AmortizareLuna]
				WHEN [AmixRegistru].[RegimAmortizare]= 2 THEN d.[AmortizareLuna]
				WHEN [AmixRegistru].[RegimAmortizare]= 3 THEN  -- accelerata
					CASE WHEN DATEDIFF(month,[AmixRegistru].[PunereInFunctiune],@UltimaZiLuna)<12 THEN d.[AmortizareLuna]
						 WHEN DATEDIFF(month,[AmixRegistru].[PunereInFunctiune],@UltimaZiLuna)=12 THEN d.[AmortizareAn] - d.[AmortizareLuna]*11
						ELSE (d.[ValoareInventar] - d.[ValoareAmortizata] - d.[AmortizareAn])/(d.[DurataAmortizare]-12)
					END 
				ELSE 0
				END
			FROM [AmixDocumente] d
	WHERE  
		d.[Anul] = @An AND d.[Luna]=@Luna AND d.[CodUnitate]=@CodUnitate AND d.[IDTipDocument]=8 AND d.[IDMijlocFix] = [AmixRegistru].[IDMijlocFix] AND d.[IDMijlocFix] IS NOT NULL
		AND (@IDDocument=0 OR [IDDocument]=@IDDocument)
	IF @@ERROR <>0 GOTO Eroare  

	--se adauga mfixe noi
	------------------------------------------------------------------------------
	PRINT('Adauga noi MF')
	INSERT INTO [AmixRegistru]
           ([NrInventar],[Denumire],[ContAmortizare],[StocFaptic],[IDClasificare]
           ,[DataIntrare],[DataIesire],[CodUnitate],[IDDepartament],[IDStare],[ContImobilizare],[ContCheltuiala],[DurataAmortizare],[RegimAmortizare],[ValoareInventar],
			[PunereInFunctiune],[Compus],[IDGestionar],[AmortizareLuna],[AmortizareAn],[ValoareAmortizata],[CantitateOI],[IDUnitateMasura],[InFolosinta])
	(SELECT [NrInventar],[Denumire],[ContAmortizare],1,[IDClasificare],
	 CASE WHEN Compus<3 THEN DATEADD(month,1,[PunereInFunctiune]) ELSE [PunereInFunctiune] END,
	 DATEADD(month,[DurataAmortizare],[PunereInFunctiune]),
	 @CodUnitate,[IDDepartament],5,[ContImobilizare],[ContCheltuiala],[DurataAmortizare],[RegimAmortizare],[ValoareInventar],
	 [PunereInFunctiune],[Compus],[IDGestionar],[AmortizareLuna],[AmortizareAn],[ValoareAmortizata],[CantitateOI],[IDUnitateMasura],[InFolosinta]
	 FROM [AmixDocumente] ad
	 WHERE [CodUnitate]=@CodUnitate AND [IDTipDocument]=2 AND [Anul]=@An AND [Luna]=@Luna
		AND ad.[IDMijlocFix] IS NULL
		AND (@IDDocument=0 OR [IDDocument]=@IDDocument)
		AND NOT EXISTS(SELECT * FROM AmixRegistru ar WHERE ar.CodUnitate=ad.CodUnitate AND ar.NrInventar=ad.NrInventar))
		
	IF @@ERROR <>0 GOTO Eroare  
	--------------------------------------------------------------------------------
	PRINT('Face legatura cu registrul pentru toate documentele')

	UPDATE [AmixDocumente] SET [IDMijlocFix] = a.[IDMijlocFix] FROM [AmixRegistru] a
		WHERE a.[NrInventar]=[AmixDocumente].[NrInventar] AND
			  [AmixDocumente].[CodUnitate]=@CodUnitate AND [AmixDocumente].[Anul]=@An AND [AmixDocumente].[Luna]=@Luna AND [AmixDocumente].[IDMijlocFix] IS NULL
			  AND (@IDDocument=0 OR [IDDocument]=@IDDocument)
	
	IF @@ERROR <>0 GOTO Eroare  

	--Procesare Mijloace fixe compuse
	-------------------------------------------------------------------------
	IF @Compus>=1
	BEGIN
		Print('Prelucrare mijloace fixe compuse')
		UPDATE [AmixRegistru]
		SET [DataIntrare]= a2.[DataIntrare],
			[DataIesire] = a2.[DataIesire],
			[ValoareInventar] = a2.[ValoareInventar],
			[DurataAmortizare] = a2.[DurataAmortizare],
			[PunereInFunctiune] = a2.[PunereInFunctiune]
		FROM (SELECT b.[IDMFixPrincipal] AS [IDMijlocFix], 
				MIN([PunereInFunctiune]) AS [PunereInFunctiune],
				DATEDIFF(month,MIN([DataIntrare]),MAX([DataIesire]))+1 AS [DurataAmortizare],			
				SUM([ValoareInventar]) AS [ValoareInventar],
				MAX([DataIesire]) AS [DataIesire],
				MIN([DataIntrare]) AS [DataIntrare]
				FROM [AmixRegistru] a JOIN [AmixAnsamble] b ON a.[IDMijlocFix] = b.[IDMfixComponenta] 
				WHERE a.[Compus] = 2
				GROUP BY b.[IDMFixPrincipal]) a2
		WHERE 
		[Compus] = 1 AND 
		[CodUnitate]=@CodUnitate AND 
		[AmixRegistru].[IDMijlocFix] = a2.[IDMijlocFix]
		
		IF @@ERROR <>0 GOTO Eroare
	END

	Print('Conservare mijloc fix')
	----Conservare mijloc fix----------------------------------------
	UPDATE [AmixRegistru] 
			SET [IDStare] = 6
			FROM [AmixDocumente] d
	WHERE  
			d.[Anul] = @An AND d.[Luna]=@Luna AND d.[CodUnitate]=@CodUnitate AND d.[IDTipDocument]=5 AND d.[IDMijlocFix] = [AmixRegistru].[IDMijlocFix] AND d.[IDMijlocFix] IS NOT NULL
			AND (@IDDocument=0 OR [IDDocument]=@IDDocument)
	IF @@ERROR <>0 GOTO Eroare  
	--------------------------------------------------------------------

	----Reactivare mijloc fix-------------------------------------------

	DECLARE @recalcul int
	SET @recalcul=0	
	Print('Reactivare mijloc fix')

	UPDATE [AmixRegistru] 
			SET [IDStare] = 5,
			[PunereInFunctiune] = d.[PunereInFunctiune]
			FROM [AmixDocumente] d
	WHERE  
			d.[Anul] = @An AND d.[Luna]=@Luna AND d.[CodUnitate]=@CodUnitate AND d.[IDTipDocument]=6 AND d.[IDMijlocFix] = [AmixRegistru].[IDMijlocFix] AND d.[IDMijlocFix] IS NOT NULL
			AND (@IDDocument=0 OR [IDDocument]=@IDDocument)
	IF @@ERROR <>0 GOTO Eroare  
	--------------------------------------------------------------------
	IF @AnCurent*12 + @LunaCurenta <= @An*12+@Luna
	BEGIN
		PRINT('Calcul Amortizare lunara si pentru ultima luna')
		-- generare amortizare  luna curenta pentru mijloace fixe obisnuite
		INSERT INTO [AmixAmortizare]
		   ([IDMijlocFix],[Luna],[An],[ValoareInventar],[ValoareAmortizata],[ValoareRamasa]
		   ,[AmortizareAn],[AmortizareLuna],[DurataNormata],[LuniAmortizate])	
		SELECT [IDMijlocFix],
		@Luna,@An,ar.[ValoareInventar],ar.ValoareAmortizata,ar.[ValoareInventar] - ar.ValoareAmortizata,ar.[AmortizareAn],
		ar.[AmortizareLuna],[DurataAmortizare],
		CASE WHEN (DATEDIFF(month,[PunereInFunctiune],@UltimaZiLuna)-1) < 0 THEN 0
		ELSE (DATEDIFF(month,[PunereInFunctiune],@UltimaZiLuna)-1) END -- numarul de luni amortizare
		FROM [AmixRegistru] ar
		WHERE [CodUnitate]=@CodUnitate AND [RegimAmortizare]<>0 AND [Compus]<>1
		AND ar.[IDMijlocFix] NOT IN (SELECT [IDMijlocFix] FROM [AmixDocumente] d
			WHERE  d.[Anul] = @An AND d.[Luna]=@Luna AND d.[CodUnitate]=@CodUnitate AND d.[IDTipDocument]=3 
			AND (@IDDocument=0 OR [IDDocument]=@IDDocument))
		AND ar.[IDStare]=5 AND (YEAR([PunereInFunctiune])*100+MONTH([PunereInFunctiune]) < YEAR(@UltimaZiLuna)*100+MONTH(@UltimaZiLuna))
		IF @@ERROR <>0 GOTO Eroare  	


		--generare amortizare mijloace compuse
		-----------------------------------------------------------------------------------
		
		IF @Compus >= 1
		BEGIN
			Print('Prelucrare amortizare mijloace fixe compuse')
			
			INSERT INTO [AmixAmortizare]
			   ([IDMijlocFix],[Luna],[An],[ValoareInventar],[ValoareAmortizata],[ValoareRamasa]
			   ,[AmortizareAn],[AmortizareLuna],[DurataNormata],[LuniAmortizate])
			(SELECT b.[IDMFixPrincipal],
				@Luna,@An,
				r1.[ValoareInventar],
				SUM(ISNULL(a.[ValoareAmortizata],0)), 
				SUM(ISNULL(a.[ValoareRamasa],r2.[ValoareInventar])),
				SUM(ISNULL(a.[AmortizareAn],0)),
				SUM(ISNULL(a.[AmortizareLuna],0)),
				r1.[DurataAmortizare],
				CASE WHEN DATEDIFF(month,r1.[PunereInFunctiune],@UltimaZiLuna)-1 < 0 THEN 0
					 ELSE DATEDIFF(month,r1.[PunereInFunctiune],@UltimaZiLuna)-1 END
			FROM [AmixAnsamble] b
				LEFT OUTER JOIN [AmixAmortizare] a   ON a.[IDMijlocFix] = b.[IDMfixComponenta] AND a.[Luna] = @Luna AND a.[An]=@An
				JOIN [AmixRegistru] r2 ON b.[IDMfixComponenta]  = r2.[IDMijlocFix] 
				JOIN [AmixRegistru] r1 ON b.[IDMFixPrincipal] = r1.[IDMijlocFix]
			WHERE 
				(YEAR(r1.[PunereInFunctiune])*12 + MONTH(r1.[PunereInFunctiune])+1 <= @An*12+@luna) AND --din luna urmatoare datei de punere in functiune
				(@An*12+@Luna <= YEAR(r1.[PunereInFunctiune])*12+MONTH(r1.[PunereInFunctiune]) + r1.[DurataAmortizare])
				AND r1.[CodUnitate]=@CodUnitate  
				AND r2.[IDStare]=5
		   GROUP BY b.[IDMFixPrincipal],r1.[ValoareInventar],r1.[DurataAmortizare],r1.[PunereInFunctiune])

			IF @@ERROR <>0 GOTO Eroare  	

		END	
	END
	
	Print('actualizeaza valorile pentru documentele compuse')
	--actualizeaza valorile pentru documentele compuse
	UPDATE [AmixDocumente] SET [ValoareInventar] = a.[ValoareInventar],
	[ValoareAmortizata] = a.[ValoareAmortizata]
	FROM [AmixRegistru] a WHERE [AmixDocumente].[CodUnitate]=@CodUnitate
	AND [AmixDocumente].[IDMijlocFix]=a.[IDMijlocFix] AND [AmixDocumente].[Luna]=@Luna AND [AmixDocumente].[Anul]=@An
	AND [AmixDocumente].[Compus]=1
	IF @@ERROR <>0 GOTO Eroare

	

	----Blocheaza amortizarea mijloacelor fixe care pleaca din gestiune
	----trece mijloacele in mijloace iesite
	Print('trece mijloacele in mijloace iesite')
	UPDATE [AmixRegistru] 
			SET [IDStare] = 2,[InFolosinta]=0
			FROM [AmixDocumente] d
		WHERE  
			d.[Anul] = @An AND d.[Luna]=@Luna AND d.[CodUnitate]=@CodUnitate AND d.[IDTipDocument]=3 AND d.[IDMijlocFix] = [AmixRegistru].[IDMijlocFix] AND d.[IDMijlocFix] IS NOT NULL
			AND (@IDDocument=0 OR [IDDocument]=@IDDocument)
	IF @@ERROR <>0 GOTO Eroare  
	-- Blocheaza amortizarile pentru mijloacele fixe care pleaca din gestiune
	Print('Blocheaza amortizarile pentru mijloacele fixe care pleaca din gestiune')
	UPDATE [AmixAmortizare] 
				SET [Blocat] = 1
				FROM [AmixDocumente] d
			WHERE  
				d.[Anul] = @An AND d.[Luna]=@Luna AND d.[CodUnitate]=@CodUnitate AND d.[IDTipDocument]=3 AND d.[IDMijlocFix] = [AmixAmortizare].[IDMijlocFix] AND d.[IDMijlocFix] IS NOT NULL
				AND (@IDDocument=0 OR [IDDocument]=@IDDocument)
				AND [AmixAmortizare].[An]*100 + [AmixAmortizare].[Luna] >= @An*100+@Luna
	IF @@ERROR <>0 GOTO Eroare  

	Print('Transfer intern, schimbare gestionar')
	----Transfer intern, schimbare gestionar
	UPDATE [AmixRegistru] 
			SET [IDDepartament] = d.[IDDepartament],
			[IDgestionar] = d.[IDGestionar]
			FROM [AmixDocumente] d
		WHERE  
			d.[Anul] = @An AND d.[Luna]=@Luna AND d.[CodUnitate]=@CodUnitate AND d.[IDTipDocument]=4 AND d.[IDMijlocFix] = [AmixRegistru].[IDMijlocFix] AND d.[IDMijlocFix] IS NOT NULL
			AND (@IDDocument=0 OR [IDDocument]=@IDDocument)
	IF @@ERROR <>0 GOTO Eroare  




	Print('Inchidere Luna')
	----------- inchidere luna
	IF @InchideLuna=1
	BEGIN
		DECLARE @azi DateTime
		SET @azi = CAST(CAST(@An as varchar(4)) + '-' + cast(@Luna as varchar(2)) + '-01' AS DateTime)
		UPDATE [AmixSetup] SET [LunaCurenta]= MONTH(DATEADD(month,1,@azi)),[AnulCurent]=YEAR(DATEADD(month,1,@azi))
		WHERE [CodUnitate]=@CodUnitate
		IF @@ERROR <>0 GOTO Eroare 
		SET @Luna = MONTH(DATEADD(month,1,@azi))
		SET @An = YEAR(DATEADD(month,1,@azi))


		Print('Schimba stare mijloace amortizate')
		UPDATE [AmixRegistru] SET [AmortizareLuna] = 0,[AmortizareAn]=0,[IDStare]=1
		WHERE 
		[AmixRegistru].[CodUnitate]=@CodUnitate  AND [ValoareAmortizata] + AmortizareLuna >= [ValoareInventar] AND  [ValoareAmortizata] >= [ValoareInventar]
		AND [IDStare]=5
		IF @@ERROR <>0 GOTO Eroare


		Print('actualizeaza in registru valoarea de inventar si valoare amortizata in ultima luna')
		UPDATE [AmixRegistru] SET [AmortizareLuna] = [ValoareInventar] - [ValoareAmortizata],
		[ValoareAmortizata] = [ValoareInventar],[LuniAmortizate] = DurataAmortizare
		WHERE 
		[AmixRegistru].[CodUnitate]=@CodUnitate  AND [ValoareAmortizata] + AmortizareLuna >= [ValoareInventar] AND  [ValoareAmortizata] < [ValoareInventar]
		AND [IDStare]=5
		IF @@ERROR <>0 GOTO Eroare


		Print('actualizeaza in registru valoarea de inventar si valoare amortizata')
		--actualizeaza in registru valoarea de inventar si valoare amortizata
		UPDATE [AmixRegistru] SET 
		[ValoareAmortizata] = [ValoareAmortizata]+AmortizareLuna,[LuniAmortizate] = [LuniAmortizate]+1
		WHERE 
		[AmixRegistru].[CodUnitate]=@CodUnitate AND [ValoareAmortizata]+AmortizareLuna <[ValoareInventar]
		AND [IDStare]=5
		IF @@ERROR <>0 GOTO Eroare


	
		EXEC [amix_InchideLuna2] @Luna,@An,@CodUnitate,0,0;
	END 
	COMMIT

	---inchidere luna

	GOTO Gata
	DUBLURI:
		RAISERROR ('Exista mijloace fixe cu acelasi numar de inventar',16,-1)
		GOTO Gata

	EROARE:
		ROLLBACK
		RAISERROR ('Eroare la prelucrarea datelor',16,-1)
		GOTO Gata

		GATA:
END



GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[exbug_GenereazaExecutieCheltuieli]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[exbug_GenereazaExecutieCheltuieli]
GO



CREATE PROCEDURE [dbo].[exbug_GenereazaExecutieCheltuieli]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint, 
	@Data datetime,
	@IDDepartament int,
	@IDJurnal int
AS
BEGIN
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	INSERT INTO [ExecutieCheltuieli]
           ([ArtAl]
           ,[Data]
           ,[Valoare]
           ,[CodUnitate]
           ,[IDJurnal]
           ,[IDDepartament])
     SELECT [ArtAl],@Data,0,@CodUnitate,@IDJurnal,@IDDepartament  FROM [ArticoleAliniate] a WHERE [CodUnitate]=@CodUnitate and a.ExecutieCheltuieli=1 
     AND NOT EXISTS(SELECT * FROM [ExecutieCheltuieli] e WHERE a.ArtAl= e.ArtAl AND a.CodUnitate=e.CodUnitate and MONTH(e.Data)=Month(@Data)and YEAR(e.Data)=YEAR(@Data)  and e.IDDepartament = @IDDepartament
     AND e.IDJurnal = @IDJurnal)
     
     DELETE FROM [ExecutieCheltuieli] WHERE 
     NOT EXISTS(SELECT * FROM [ArticoleAliniate] a  WHERE [ExecutieCheltuieli].ArtAl= a.ArtAl AND a.CodUnitate=@CodUnitate AND a.ExecutieCheltuieli=1)
      and MONTH([ExecutieCheltuieli].Data)=Month(@Data) and YEAR([ExecutieCheltuieli].Data)=YEAR(@Data) and [ExecutieCheltuieli].IDDepartament = @IDDepartament
     AND [ExecutieCheltuieli].IDJurnal = @IDJurnal AND [ExecutieCheltuieli].CodUnitate=@CodUnitate

END


GO


IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Departamente' AND COLUMN_NAME = 'ExecutieCheltuieli')
BEGIN
	ALTER TABLE dbo.Departamente ADD ExecutieCheltuieli bit NOT NULL DEFAULT 0
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[amix_GetObiecteInventar]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[amix_GetObiecteInventar]
GO


CREATE PROCEDURE [dbo].[amix_GetObiecteInventar]
	@CodUnitate smallint,
	@FiltruDep varchar(8000),
	@Luna smallint,
	@Anul smallint
AS
BEGIN
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	SELECT ar.*,um.Prescurtare UMDenumire,dp.Nume LocDepozitare,dp2.Nume NumeGestiune FROM AmixRegistru ar JOIN UnitatiMasura um ON ar.IDUnitateMasura = um.IDUnitateMasura
	JOIN Departamente dp ON ar.IDDepartament=dp.IDDepartament AND dp.CodUnitate = ar.CodUnitate
	LEFT OUTER JOIN	Departamente dp2 ON dp.IDDepartParinte = dp2.IDDepartament AND dp.CodUnitate = dp2.CodUnitate
	Where ar.CodUnitate = @CodUnitate AND ar.Compus >=3 AND
	(LEN(LTRIM(RTRIM(@FiltruDep)))=0 OR (ar.IDDepartament IN (SELECT fart.value FROM dbo.SplitIntParameters(@FiltruDep,',') fart)))
	AND YEAR([DataIntrare])*100 + MONTH([DataIntrare]) <= @Anul*100 + @Luna
    AND ar.InFolosinta=1
END


GO


IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[AmixViewDocumente]'))
DROP VIEW [dbo].[AmixViewDocumente]
GO


CREATE VIEW [dbo].[AmixViewDocumente]
AS
SELECT     dbo.AmixDocumente.NumarDoc, dbo.AmixDocumente.DataDoc, dbo.AmixDocumente.IDTipDocument, dbo.TipDocument.Denumire AS DenumireDocument, 
                      dbo.Departamente.Nume AS LocFunctionare, dbo.AmixDocumente.NrInventar, dbo.AmixDocumente.Denumire, dbo.AmixCatalog.Cod AS codClasificare, 
                      dbo.AmixTipModDocument.Denumire AS Modalitate, dbo.AmixDocumente.ContAmortizare, dbo.AmixDocumente.ContCheltuiala, dbo.AmixDocumente.ContImobilizare, 
                      dbo.AmixDocumente.ContTransfer, dbo.AmixDocumente.PunereInFunctiune, dbo.AmixGestionari.Nume AS Gestionar, dbo.AmixDocumente.ValoareInventar, 
                      dbo.AmixDocumente.DurataAmortizare, 
                      CASE WHEN dbo.AmixDocumente.RegimAmortizare = 0 THEN 'Fara Amortizare' WHEN dbo.AmixDocumente.RegimAmortizare = 1 THEN 'Amortizare Liniara' WHEN dbo.AmixDocumente.RegimAmortizare
                       = 2 THEN 'Amortizare Accelerata' WHEN dbo.AmixDocumente.RegimAmortizare = 3 THEN 'Amortizare degresiva' ELSE '' END AS RegimAmortizare, 
                      dbo.AmixDocumente.ComisiaRec AS Observatii, dbo.AmixDocumente.CodUnitate, dbo.AmixDocumente.Luna, dbo.AmixDocumente.Anul, 
                      dbo.AmixDocumente.AmortizareLuna, dbo.AmixDocumente.AmortizareAn, dbo.AmixDocumente.ValoareAmortizata, dbo.AmixDocumente.ValoareSuplimentara, 
                      dbo.AmixDocumente.IDMijlocFix, 
                      CASE WHEN dbo.AmixDocumente.Compus = 0 THEN 'Mijloc Fix' WHEN dbo.AmixDocumente.Compus = 1 THEN 'Mijloc Fix Compus' WHEN dbo.AmixDocumente.Compus
                       = 2 THEN 'Mijloc Fix Componenta' ELSE '' END AS TipMijlocFix, dbo.AmixDocumente.Compus, dbo.AmixDocumente.AmortizarePrimulAn, 
                      dbo.AmixDocumente.Categorie, dbo.AmixDocumente.ContTransferForSuperior, dbo.AmixDocumente.IDUnitateMasura, dbo.AmixDocumente.CantitateOI
FROM         dbo.AmixDocumente INNER JOIN
                      dbo.TipDocument ON dbo.AmixDocumente.IDTipDocument = dbo.TipDocument.IDTipDocument LEFT OUTER JOIN
                      dbo.Departamente ON dbo.AmixDocumente.IDDepartament = dbo.Departamente.IDDepartament LEFT OUTER JOIN
                      dbo.AmixCatalog ON dbo.AmixDocumente.IdClasificare = dbo.AmixCatalog.IDClasificare LEFT OUTER JOIN
                      dbo.AmixTipModDocument ON dbo.AmixDocumente.IDMod = dbo.AmixTipModDocument.IDMod LEFT OUTER JOIN
                      dbo.AmixGestionari ON dbo.AmixDocumente.IDGestionar = dbo.AmixGestionari.IDGestionar

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[amix_CentralizatorTransfer]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[amix_CentralizatorTransfer]
GO


CREATE PROCEDURE [dbo].[amix_CentralizatorTransfer]	
	@CodUnitate smallint, 
	@Luna smallint,
	@Anul smallint
AS
BEGIN
	SET NOCOUNT ON;
    DECLARE @lunaAnt smallint
    DECLARE @anAnt smallint
    
    IF @Luna=12
    BEGIN
		SET @lunaAnt=1
		SET @anAnt = @Anul -1
	END
	ELSE
	BEGIN
		SET @lunaAnt = @Luna-1
		SET @AnAnt = @Anul
	END	
    
	select 
	ar.NrInventar, ar.ValoareInventar*ar.CantitateOI ValoareInventar,ar.Denumire,um.Denumire,
	--count(*) Nr_transferate,sum(ar.ValoareInventar*ar.CantitateOI) Valoare_Transferata,
	d4.Nume sursa,d3.Nume dest FROM AmixDocumente ad
	JOIN AmixRegistru ar ON ar.NrInventar=ad.NrInventar
	JOIN Departamente d1 ON ar.IDDepartament = d1.IDDepartament
	JOIN Departamente d3 ON d1.IDDepartParinte = d3.IDDepartament
	JOIN AmixRegistruBK arb ON arb.NrInventar=ad.NrInventar
	JOIN Departamente d2 ON arb.IDDepartament = d2.IDDepartament
	JOIN Departamente d4 ON d2.IDDepartParinte = d4.IDDepartament
	JOIN UnitatiMasura um ON ar.IDUnitateMasura = um.IDUnitateMasura
	where ad.compus>=3
	AND ad.Luna=@luna AND ad.Anul=@anul
	and arb.Luna=@lunaAnt and arb.An=@anAnt
	and ad.IDTipdocument=4
	order by d4.Nume,d3.Nume

END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[amix_CentralizatorIntrari]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[amix_CentralizatorIntrari]
GO

CREATE PROCEDURE [dbo].[amix_CentralizatorIntrari]	
	@CodUnitate smallint, 
	@Luna smallint,
	@Anul smallint
AS
BEGIN
	SET NOCOUNT ON;
    
	select 
	ar.NrInventar, ar.ValoareInventar*ar.CantitateOI ValoareInventar,ar.Denumire,um.Denumire,
	--count(*) Nr_transferate,sum(ar.ValoareInventar*ar.CantitateOI) Valoare_Transferata,
	d3.Nume dest FROM AmixDocumente ad
	JOIN AmixRegistru ar ON ar.NrInventar=ad.NrInventar
	JOIN Departamente d1 ON ar.IDDepartament = d1.IDDepartament
	JOIN Departamente d3 ON d1.IDDepartParinte = d3.IDDepartament
	JOIN UnitatiMasura um ON ar.IDUnitateMasura = um.IDUnitateMasura
	where ad.compus>=3
	AND ad.Luna=@luna AND ad.Anul=@anul
	and ad.IDTipdocument=2
	order by d3.Nume

END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[exbug_GenereazaExecutieCheltuieliTotal]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[exbug_GenereazaExecutieCheltuieliTotal]
GO

CREATE PROCEDURE [dbo].[exbug_GenereazaExecutieCheltuieliTotal]
	-- Add the parameters for the stored procedure here
	@CodUnitate smallint, 
	@Data datetime,
	@IDDepartament int,
	@IDJurnal int
AS
BEGIN
	SET NOCOUNT ON;

     
     SELECT SUBSTRING(ArtAl,1,2) Articol, SUM(Valoare) Total FROM [ExecutieCheltuieli] a WHERE 
     MONTH(a.Data)=Month(@Data) and YEAR(a.Data)=YEAR(@Data) and a.IDDepartament = @IDDepartament
     AND a.IDJurnal = @IDJurnal AND a.CodUnitate=@CodUnitate
     GROUP BY SUBSTRING(ArtAl,1,2)
     ORDER BY Articol

END

GO

